The Math(cmath) library allows you to calculate trigonometric function cos(x). You can execute this method by writing cos(x) for some expression x of type double. Using properties of a Maclaurin series or Taylor series, you can approximate the function cos(x) using the following formula: cos(� ≈ ∑ (−1)���(2�! ��0 =1− � 2!+ � 4!− � 6!+ � 8!− ..... ��2� 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 <bits/stdc++.h>
using namespace std;
const double PI = 3.142;
double calcTerm(){
double x;
x = x * (PI / 180.0);
double sum = 1;
double S = 1, ser = 1, pow = 1;
for (int i = 1; i < 5; i++) {
S = S * -1;
ser = ser * (2 * i - 1) * (2 * i);
pow = pow * x * x;}}
double SumSeries(double x, int num)
{
x = x * (PI / 180.0);
double sum = 1;
double S = 1, ser = 1, pow = 1;
for (int i = 1; i < 5; i++) {
S = S * -1;
ser = ser * (2 * i - 1) * (2 * i);
pow = pow * x * x;
sum = sum + S * pow / ser;
}
return sum;
}
int main()
{
float x = 40;
int num = 4;
calcTerm();
cout << "Sum of the series is: "<<SumSeries(x, 4);
return 0;
}
Comments
Leave a comment