Using properties of a Maclaurin series
or Taylor series, you can approximate the function cos(x) using the following
formula:
cos(x) ≈ ∑ (−1)
n
x
2n
(2n)!
a
n=0
= 1 −
x
2
2!
+
x
4
4!
−
x
6
6!
+
x
8
8!
− . . . ..
x
2a
2a!
Write your own approximation of cos(x) without using any library methods (such as pow( ) etc.). Your
program should take x (in radians) and an as input. You should make two functions calcTerm( ) and
sumTerms( ) to calculate the value of cos(x). calcTerm( ) function will compute nth term in the sequence.
It should take x and term number as arguments and the return value of the term. sumTerms( ) takes a
single argument term value and should be used to calculate the sum of all terms. Finally, your program
will have a function testFunction( ), you will call it from main to verify whether your function is working
correctly or not.
#include <iostream>
#include <cmath>
using namespace std;
double calcTerm(double x, int n);
double sumTerms(double x);
void testFunction(double x);
int main()
{
double x;
cout << "Enter value of x (in rad): ";
cin >> x;
testFunction(x);
}
double calcTerm(double x, int n) {
double term=1;
for (int i=0; i<n; i++) {
term *= -x*x;
term /= (2*i+1) * (2*i+2);
}
return term;
}
double sumTerms(double x) {
double s = 0;
int i = 0;
while (true) {
double term = calcTerm(x, i);
s += term;
if (abs(term) < 1e-15) {
break;
}
i++;
}
return s;
}
void testFunction(double x) {
double calcCos = sumTerms(x);
double realCos = cos(x);
double err = calcCos - realCos;
cout << "Calculated value is " << calcCos << endl;
cout << "Real value of cos is " << realCos << endl;
cout << "Error: " << err << endl;
}
Comments
Leave a comment