Reputation: 120
Since I have learnt Horner's rule recently. I decided to evaluate sinx using the same with the help of taylor series. I wrote some code, but its showing some great deviation from the original result.
#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
So, passing the parameters as the one mentioned above, the expected result should be 0.841 but when my program is calculating, it shows 0.735. I also tried giving n as a very large number, but it is showing greater deviation than before. Any help would be highly appreciated. Thanking you in advance!!
Upvotes: 3
Views: 957
Reputation: 990
Based on the comment by @Ted Lyngmo, here is a working version, with minor modifications.
In your original code you can do 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;
}
I also suggest you check your formula with x != 1
since it's harder to miss multiplicative x
factors that way.
Upvotes: 3