Loop returns nan

I know that there are more elegant solutions to this problem than what I'm using, but I've been asked to compose this for a class, not using the pow() function, and frankly, I don't want to use codes that are beyond the scope of the class so far. This code should use the first 10 x terms of a Taylor series:

cos(x) = 1 - x^2/2! + x^4/4! - x^6/6! ...

It's perfectly functional for its purpose, but if I set i equal to 34 or above (meaning, expanding the code out to x^34/34!), it begins to return 'nan' for the function, and I was wondering if someone could explain why.

Thank you very much! Not really necessary for my purposes here, but I'd like to know what's going one. It seems like I should be able to keep increasing this value, converging on the value given by the cos() function in cmath.

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

main()

{

double angledegree, anglerad, pi=acos(-1), cosvalue(1), xpower;
int fact, i(2), topfact;
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(50);

cout<<"Input an angle (in degrees) between 0 and 90.\n";
cin>>angledegree;
anglerad = angledegree*(pi/180);

while(i<=34)
{
fact=1;
for (int s=1; s<=i; s++)
{
fact=s*fact;
}
xpower=1;
for (int t=1; t<=i; t++)
{
xpower=xpower*anglerad;
}

cosvalue=cosvalue-(xpower/fact);
i=i+2;

fact=1;
for (int s=1; s<=i; s++)
{
fact=s*fact;
}

xpower=1;
for (int t=1; t<=i; t++)
{
xpower=xpower*anglerad;
}

i=i+2;
cosvalue=cosvalue+(xpower/fact);

}

cout<<"Value according to our function, below.\n";
cout<<cosvalue<<endl;
cout<<cos(anglerad)<<endl;
cout<<"Value according to cos() above.\n";


return 0;
}
Last edited on
*Note: I declared a 'double topfact' that is extraneous to how I eventually wrote the code.*
The problem is that the factorial value gets too large to be stored in an int. Changing fact to a double should fix it.
You're a saint, Peter. That works perfectly. Coding: you only learn by making mistakes. Thank you very much!
Topic archived. No new replies allowed.