About half year ago, I derived a integral of a piecewise polynomial, which was a complex formula. Below is one of that formula:
Obviously, the above formula has relationship with four varibles \$u_i,\cdots u_{i+3}\$.
In the begining, I implement it in Wolfram Mathematica with the help of Compile[]
technique and corresponding option like CompilationTarget -> "C"
. The screenshot as shown below:
Recently, I would like to rewrite it to C to achieve more higher performance.
#include <math.h>
#include <stdio.h>
//calc_A()
double calc_A(int i, const double *U) {
double u0, u1, u2, u3;
double res;
u0 = U[i];
u1 = U[i+1];
u2 = U[i+2];
u3 = U[i+3];
//implementation of the explicit formula
res = 3 * pow(u1, 4) + 3 * pow(u1, 3)*(u2 - 2 * u3) +
pow(u1, 2)*(3 * pow(u2, 2) - 7 * u2*u3 + 3 * pow(u3, 2)) +
u1*u2*(3 * pow(u2, 2) - 8 * u2*u3 + 4 * pow(u3, 2)) +
pow(u2, 2)*(3 * pow(u2, 2) - 9 * u2*u3 + 8 * pow(u3, 2)) +
pow(u0, 2)*(8 * pow(u1, 2) + 3 * pow(u2, 2) + 4 * u1*(u2 - 5 * u3) - 10 * u2*u3 +
15 * pow(u3, 2)) - u0*(9 * pow(u1, 3) + pow(u1, 2)*(8 * u2 - 19 * u3) +
u1*(7 * pow(u2, 2) - 22 * u2*u3 + 10 * pow(u3, 2)) +
u2*(6 * pow(u2, 2) - 19 * u2*u3 + 20 * pow(u3, 2)));
return res;
}
int main() {
double U[] = { 0., 0., 0., 0., 0.2, 0.25, 0.4, 0.6, 0.8, 1., 1., 1., 1. };
int i;
double res;
//calculate A[2]~A[6]
for (i = 2; i <= 6; i++) {
res = calc_A(i, U);
printf("%f\n", res);
}
system("pause");
return 0;
}
where, \$\mathbf U=\{u_0,\cdots,u_m\}\$
TEST
According to my experience, the code for res
is inefficient, but I don't know how to deal with it by myself.
res
is a variable of typedouble
. Not sure what you mean by that question. I don't see any human optimizations here. The compiler may make some optimizations of the formulae but that should be nothing for you to worry about. \$\endgroup\$pow
is not a fast function; that is where your optimization efforts need to be focused. But first, you need to actually ensure that the code runs too slowly, rather than simply presuming that it is inefficient. What is your desired speed range? How far off are you currently? \$\endgroup\$