User created cosine function producing incorrect output

I need to create a cosine function that mimics the standard cos() function using McLauren's Series. I have already correctly implemented a sine function. The problem might be with the logic for the power and factorial in the for loop. For example, I used 82 degrees as the angle and the output was 0.570343. The correct output would be 0.139173

1
2
3
4
5
6
7
8
9
10
#include"Header.h"
double cosex(double n)
{
        double cx,x;
	x=n*PI/180;
	cx=x;
	for(int i=1;i<40;i++)
	    cx+= pow(-1.0,i)*pow(x,2*i )/fact(2*i);
	return(cx);
}
Last edited on
http://mathworld.wolfram.com/images/equations/MaclaurinSeries/Inline41.gif

Might have to do with the way your fact method works. Note that factorial of 20 is already larger than what most integer types in c++ can represent accurately
Last edited on
Can you cheat and use sinex( n + PI/2.0 ) ?
(How did you implement the sine function?)
Duoas: I tried your work around, but the output was 0.993711

Smac89: Here is my factorial function...
1
2
3
4
5
6
7
8
9
10
11
double fact(int n)
{
	double f;
	f=1;
	if (n==0 || n==1)
		return 1;
	for (int i=1;i<=n;i++)
		f*=double(i);
		return f;
}
You are getting an overflow. 40! Is well over an integer, let alone 80!. Try only doing a few iterations, 6 is the most for an integer.
I changed the condition in the cos() function to i<7, but still got 0.570343. Any other ideas?
1
2
3
4
5
6
7
8
9
double cosex(double n)
{
        double cx,x;
	x=n*PI/180;
	cx=x;
	for(int i=1;i<40;i++)
	    cx+= pow(-1.0,i)*pow(x,2*i )/fact(2*i);
	return(cx);
}

Here's the series:
cos x = 1 - x2/2! + x4/4! - ...

Note the first term is 1.
So change line 5 to cx = 1;
The nice way to do it is to not use factorial, but instead to calculate the next term from the current one:

1
2
3
4
5
6
7
double term=1.;
double cx=1.;
for(int i=2;i<=80;i+=2)
{
    term=-term*x*x/(1.0*i*(i-1));
    cx+=term;
}

This will get rid of overflow.
Last edited on
@ats15 Good suggestion. It also cuts out an enormous amount of repeated or unnecessary calculation in the pow() and fact() functions.
Chervil: Thank you, your suggestion worked.
Topic archived. No new replies allowed.