cos(x) = 1 - (x^2)/2! + (x^4)/4! - (x^6)/6! + ......
Now, I've written two programs, both of which use while loops, however they have diffrent terminating conditions. And, for smaller values of x they both get the exact answer you would when you use the cosine function in <cmath>. However, if you choose x to be 100 or something, there's a huge discrepancy between my program's answer and cmath.
I'm worried that I might be initializing the values of term and the sums incorrectly. If I'm not, then I'm stumped as to what i'm doing wrong! Here's my code, and if you guys can maybe make a suggestion, it would be sweet!
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
double x, term = 1, oldsum = 0, newsum = term;
int i = 1;
cout<<"Enter value of x in radians:"<<endl;
cin>>x;
while(oldsum != newsum)
*/the loop should stop when there's no more diffrence between the old and new sum (i.e the term has become too small to make a diffrence) */
{
oldsum = newsum;
term = fabs(term)*pow(-1.0,i)*pow(x,2)/(2*i*(2*i-1));
newsum += term;
++i;
}
cout<<"cos("<<x<<") = "<<newsum<<endl;
cout<<"cos("<<x<<") = "<<cos(x)<<endl;
system("pause");
return 0;
}
Edited by Jaan, 21 September 2009 - 08:41 AM.


Sign In
Create Account

Back to top










