简体   繁体   English

“解码”正弦泰勒级数的近似值

[英]“decode” an approximation of sin Taylor series

I'm using Taylor series to compute sin() . 我正在使用泰勒级数来计算sin() The Taylor series for the sin are: 罪恶的泰勒级数是:

罪恶泰勒系列

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 . 据我了解,该代码是多项式的j项的近似值(换句话说,该近似值是从零到j的求和,而不是从零到∞的求和),公式中的kn ,当然xx

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. 我的目标是为cos()系列编写相同类型的实现。

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. 这是McLaurin系列,但编写该系列文章的目的是为了减少利用该系列通用术语的递归公式进行计算的次数。

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) 编辑 (用LaTeX创建的图像替换了难看的文本数学)

To understand the trick, let's focus on the sine example and recall the McLaurin expansion of the sine function: 为了理解这个技巧,让我们集中在sine示例上,并回顾正弦函数的McLaurin扩展:

McLaurin扩展正弦函数

Now let's perform the expansion up to the 5th term (N=5), neglect the remainder R and perform some rewriting involving factorizations of x 2 terms. 现在,让我们执行直到第5个项的扩展(N = 5),忽略其余的R并执行一些涉及x 2项分解的重写。 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, ie 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 ) . C函数只是自下而上的递归重写的实现,即,上述模式中最后一步出现的是首先在sine函数中计算的(该示例相对于j==4的调用而言,因此循环变量k的起始值为3 ,下降到0 )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM