It is a McLaurin series, but it is written so as to reduce the number of computations exploiting a recurrence formula for the general term of the series.
The version for cosine is the following (together with a simple test harness):
#include <stdio.h>
#include <math.h>
float cosine(float x, int j)
{
float val = 1;
for (int k = j - 1; k >= 0; --k)
val = 1 - x*x/(2*k+2)/(2*k+1)*val;
return val;
}
int main( void )
{
for( double x = 0.0; x <= 1.57; x += 0.1 )
{
printf("%10g %10g %10g\n", x, cos(x), cosine(x, 5));
}
return 0;
}
EDIT (replaced ugly text math with images created with LaTeX)
To understand the trick, let's focus on the sine
example and recall the McLaurin expansion of the sine function:
Now let's perform the expansion up to the 5th term (N=5), neglect the remainder R and perform some rewriting involving factorizations of x2 terms. The resulting steps are described below, where rewritten subexpressions are marked with a number in square brackets:
The C function is just the implementation of this recursive rewriting from the bottom up, i.e. what appears as the last step in the above schema is computed first in the sine
function (the example is relative to a call with j==4
, so that the loop variable k
starts with a value of 3
and goes down to 0
) .