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;
}
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.
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.