cosine approximation

Hello, I'm trying to work on a cosine approximation program by using a Taylor series.

The basic format is:

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

I'm having trouble, I think it's with the denominator. Can someone help me out?

This is what I have so far:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
#include <cmath>
using namespace std;

int factorial(int);

int main () {
	
	int angle, n, numOfTerms;
	long double radAngle, numerator=1, denominator=2, cosine=1, temp=0, pi=3.14159;
	
	cout << "Input an angle in degrees between 0 and 90: \n";
	cin >> angle;
	cout << "Enter number of terms: \n";
	cin >> numOfTerms;
	
	
	radAngle = pi*angle/180;
	
	for (n=0; n <= numOfTerms - 1; n++) {
		cosine = cosine + pow(-1.0, n)*temp;
		numerator = numerator*radAngle*radAngle;
		denominator = (denominator+2)*(denominator+1)*factorial(denominator);
		temp = numerator/denominator;
		
	}
	
	
	cout << "The cosine approximation at " << angle << " degrees is equal to: " << cosine << endl;
	cout << "The cosine function in the cmath library for this angle is: "<< cos (radAngle) << endl;
	cout << factorial(numOfTerms) << endl;
	
	return 0;
}

int factorial(int number) {
	int temp;
	
	if(number <= 1) return 1;
	
	temp = number * factorial(number - 1);
	return temp;
}
Indeed it is. I'd say
initialize denominator = 1
then for n = from 0 to numOfTerms
    ...
    numerator = -numerator * ... //that way you wont have to pow(-1, n);
    denominator = denominator * (n*2+1) * (n*2+2);
    ...
Last edited on
Hey thanks a lot!
Topic archived. No new replies allowed.