Reputation: 11
I am working on a code to calculate the cosine of a decimal number (in radians). The problem is that I can only get the correct answer when I put a small number. It uses the Taylor series.
double coseno(float x)
{
double t = x;
double cos= t;
for ( int a=1; a<20.0; ++a)
{
double mult = -x*x/((2*a)*(2*a-1));
t *= mult;
cos += t;
}
return cos;
}
Upvotes: 1
Views: 985
Reputation: 303
#include <math.h> //for M_PI
double coseno(float x){
while(x<0) x+=2*M_PI;
while(x>2*M_PI) x-=2*M_PI;
double t = 1;
double cos= t;
for ( int a=1; a<40; ++a)
{
double mult = -x*x/((2*a)*(2*a-1));
t *= mult;
cos += t;
}
return cos;
}
Upvotes: 1
Reputation: 325
I think the problem is when you divide using / the operation is not evaluated with the precision you need. When you use small values the approximation is enough to get the correct result but when you use bigger values you get into an approximation problem.
You repeat the approximation error many times inside the for loop and so you get wronger result as the input increases
Upvotes: 0