Search code examples
c++scientific-computing

Issue regarding calculation of sin(x) using Taylor series


I am trying to calculate the value of sin(x) without using the predefined function. Instead I am trying to calculate it using Taylor series.

The issue is that the program produces correct values for small values of x(lesser than 10 to be precise).

I have included 1000 iterations of the series but still the program produces wrong answers for larger values of x.

float e,x,p=2;
int a;
float sum1;

cout<<"enter the value x for sinx"<<endl;
cin>>x;
e=x;
sum1=x;

for(a=1;a<1000;a++)
{   
    x=x*(e/p)*(e/(p+1))*(-1);   //MULTIPLYING PREVIOUS TERM to -1*e/p * e/p+1 to get the next term.
    sum1=sum1+x;
    p=p+2;
}
cout<<sum1<<endl;

return 0;

For large values of x (example x=100) , I am getting the NaN(not a number error) which is fine by me. But the issue lies is the fact that I'm getting results like sin(25)=278.2 even though i included 1000 iterations of Taylor series.

Here is the sample output.

enter image description here

PLEASE HELP!! , I'm curious to know what went wrong.


Solution

  • While the Taylor series for sin(x) converges (because eventually the factorial in the denominator grows larger than the exponential in the numerator), for modest values of x, the values involved become very large before the quotients become very small. In every floating-point multiplication, division, addition, and subtraction, there are rounding errors. The rounding errors are roughly proportional to the values involved. (In the format commonly used for float, they average more than 2−24 times the magnitude of the result.)

    For 1000 terms, the x in your loop grows to at least 5.726•109, so the error in that term may be around 5.726•109•2−24 ≈ 341. So a final result of 278.2 is not unexpected.

    If you change to double, the errors will be smaller (around 2−53 instead of 2−24), and you will get better results for input values around 25. Nonetheless, with larger input values, the errors will grow again.