如何解决使用具有递归的霍纳规则评估sinx
自从我最近学到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
的因素。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。