سؤال

I'm using Taylor series to compute sin(). The Taylor series for the sin are:

sin taylor series

The implementation I'm using looks like follows:

float sine(float x, int j)
{
    float val = 1;

    for (int k = j - 1; k >= 0; --k)
        val = 1 - x*x/(2*k+2)/(2*k+3)*val;

    return x * val;
}

As far I understand, that code is an approximation of j terms of the polynomial (In other words, the approximation is a sumatory from zero to j instead of from zero to ∞), k is n in the formula, and of course x is x.

I'm trying to understand that implementation, that is, the transformation from the formula above to the code. My goal is to write the same kind of implementation for the cos() series.

Could you help me to understand that?

هل كانت مفيدة؟

المحلول

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:

McLaurin expansion of 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:

rewriting steps

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) .

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top