Program to evaluate sin(x) using Taylor series expansion

I run the below given program for finding sin(x) using taylor's sries expansion. but for large values of x and for large number of terms, the result shows incorrectly...for example for 180 degree and for number of terms 10 the result is like 6.53061e-007..Why is this so? how can I correct it?

The program I wrote:


#include <iostream>
#include<conio.h>

using namespace std;

int main()
{
int i,n;
float xdeg,xrad,sum,term;
cout<<"Enter the value of x in degree: ";
cin>>xdeg;
cout<<"\nEnter the number of terms: ";
cin>>n;
xrad=xdeg*3.141592/180;
term=sum=xrad;
for(i=2;i<=n;i++)
{
term*=-(xrad*xrad)/((2*i-1)*(2*i-2)));
sum+=term;
}

cout<<"\n sin("<<xdeg<<")= "<<sum<<endl;
return 0;

getch();
}

The Output

Enter the value of x in degree:180
Enter the number of terms:10
sin(180)= 6.53061e-007



6.53061e-007 means 6.53061 × 10-7 which is a small value close to the correct answer 0. You will probably get a more exact answer by adding a few decimal digits to the pi value.
Thanx..
The problem is that floating point numbers aren't exact. Using more digits for pi will help but you'll probably just get a smaller number that still isn't zero. This is just one of the difficulties in creating a math library.

You might be able to get zero if you apply some trig identities to the value in degrees first. This code will reduce the input value to an equivalent between -90 and +90 degrees.

1
2
3
4
5
6
7
8
9
    cin>>xdeg;

    xdeg = fmod(xdeg, 360);
    if (xdeg > 180) xdeg = -(xdeg - 180);
    else if (xdeg < -180) xdeg = xdeg + 360;
    // Now -180 <= xdeg <= 180

    if (xdeg > 90) xdeg = 180-xdeg;
    else if (xdeg < -90) xdeg = -180 - xdeg;


Topic archived. No new replies allowed.