Answer to Question #269094 in C++ for joey

Question #269094

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.


1
Expert's answer
2021-11-20T09:49:24-0500
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS