0

We are required to make a c++ program to determining the cos of x by using the taylor series. i have made my program and it works pretty good but we are also required to stop the loop after the terms in the taylor series gets lower than .0001. any suggestions?
(Taylor Series for cos = 1 - x^2/2! + x^4/4!...)

#include <iostream>
#include <cmath>
using namespace std;

double fac(int n)
{
double f=n;
while (--n)f*=n;
return f;
}

int main()
{
double long x;
cout << "Enter Angle in Radians: " << endl;
cin >> x;
double cos(0.0);
double temp(0.0);

for (int i=0; i<170; i++){
if (i%2 == 1)
temp = (pow(x,i*2+2))/(fac(i*2+2));
else
temp = (-1)*(pow(x,i*2+2))/(fac(i*2+2));
if (temp <= 0.0001)
break;
else
cos += temp;
}

cout << "Cosine of Angle is: " << cos << endl;

system("PAUSE");
return 0;
}
2
Contributors
1
Reply
10
Views
6 Years
Discussion Span
Last Post by Nathaniel10
0

I would use a while loop as in:

int i = 0;
while (temp < 0.0001) {
   temp = pow(-1,i) * (pow(x,i*2+2)) / (fac(i*2+2));
   cos += temp;
   i++;
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.