问题描述
自从我最近学到Horner's rule以来,。我决定在 taylor series 的帮助下使用相同的工具评估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;
}
其中n是泰勒级数的项数
因此,通过上述参数传递,预期结果应为 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
的因素。