### problems with a cosine estimation

The problem is to create a program that estimates the value of cosine using the taylor series to ten terms, WITHOUT using the pow function. The taylor series looks like this: 1-(x^2)/(2!)+(x^4)/(4!)... I used a while loop with 3 conditions and the answers I get for any angle below 45 is very close to the correct answer but when it gets anywhere closer to 90 the answer gets completely off. Any help would be appreciated. Here's the code.

#include <iostream>
#include <cmath>
using namespace std;
int main ()
{
double x,a,num,den,sign,n,part, degree;
cout<<"Enter angle in degrees: "<<endl;
cin>>degree;
x=degree*(3.141592654/180);
a=1;
n=2;
sign=(-1);
while (a<=9&&num<=x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x&&n<=18)
{
num=x*x;
den=n;
part=(num/den)*sign;
den=den*(n+1)*(n+2);
n=n+2;
sign=sign*(-1);
num=num*x*x;
a=a+1;
part=part+((num/den)*sign);
}
cout<<1+part<<endl;
return 0;
}
You need to add some couts to see what is happening (or use a debugger).
 ``1234567891011121314151617181920212223242526272829303132333435363738394041424344`` ``````#include #include using namespace std; int main () { //---------------------------------------------------- // This is the equation we are trying to calculate // // cos x = 1-x^2/2!+x^4/4!-x^6/6!+x^8/8!-... for all x // double x,a,num,den,sign,n,part, degree; cout<<"Enter angle in degrees: "; cin>>degree; //---------------------------------------------------- // Use the #define for pi x=degree*(M_PI/180.0); //---------------------------------------------------- // Print out some debugging info cout << degree << " degrees in radians is: " << x << endl; a=1; n=2; sign=(-1); //---------------------------------------------------- // Why do you check num and n? while (a<=9&&num<=x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x&&n<=18) { //-------------------------------------------------- // Debug to see what is happening cout << "a: " << a << " num: " << num << " n: " << n << endl; num=x*x; den=n; part=(num/den)*sign; den=den*(n+1)*(n+2); n=n+2; sign=sign*(-1); num=num*x*x; a=a+1; part=part+((num/den)*sign); } cout<< "cos(" << degree << ") = " << 1+part<

Why does it only run one time? Shouldn't it be running 9 time? Check the debug print outs.
After you got that, check the equation you are calculating in the while loop. Does it really represent the equation at the top of the code? Is part accumulating the end result?
It looks like these three lines are part of the initialisation and don't belong inside the loop:
 ``123`` `````` num=x*x; den=n; part=(num/den)*sign;``````

Last edited on
We've dealt with Liebniz's methed.
You need to search the forum.
Topic archived. No new replies allowed.