使用 Horner 规则递归评估 sinx

Evaluating sinx using Horner's rule with recursion

最近学习了Horner's rule。我决定在 泰勒级数 的帮助下使用相同的方法评估 sinx。我写了一些代码,但它显示出与原始结果有很大偏差。

#include<iostream>
using namespace std;

double sin(double x, int n)
{
    static double s = x;
    if(n==1)
    {
        return s;
    }
    else
    {
        s *= 1-((x*x)/((2*n-1)*(2*n-2)));
    }
    return sin(x,n-1);
}

int main()
{
    double r = sin(1,15);
    cout << r;
    return 0;
}

where n are the number of terms of the taylor series

所以,按照上面的参数传递,预期结果应该是0.841,但是当我的程序计算时,它显示0.735.我也试过给 n 作为一个非常大的数字,但它显示出比以前更大的偏差。任何帮助将不胜感激。提前致谢!!

根据@Ted Lyngmo 的评论,here 是一个工作版本,稍作修改。

在您的原始代码中,您可以执行 this:

#include<iostream>
#include <cmath>

using namespace std;

double sin(double x, int n, double s = 1)
{
    if(n==1)
    {
        return s*x;
    }
    else
    {
        s = 1 - s*((x*x)/((2*n-1)*(2*n-2)));
    }
    return sin(x, n-1, s);
}

int main()
{
    cout << "std::sin(0.5) = " << std::sin(0.5) << std::endl; 
    double r = sin(0.5, 15);
    cout << r;
    return 0;
}

我还建议您使用 x != 1 检查您的公式,因为这样更不容易遗漏乘法 x 因数。