Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

write a script file that calculates exp(2) by a Maclaurin series using a while l

ID: 3541655 • Letter: W

Question

write a script file that calculates exp(2) by a Maclaurin series using a while loop.

exp(x) = x^0 / 0! + x^1 / 1! + x^2 / 2! + x^3 / 3! + ... + x^n / n!

The while loop should add each of the series terms. The program should exit the loop when the absolute error is smaller than 0.01.

Error is the exact value (exp(2)), minus the approximate value (the current series sum).

use fprintf within the loop such that, during each round of iteration, the number of iteration, current approximation, and the absolute error are displayed.

Report exact value once at the end of the program using fprintf

Explanation / Answer

#include<cstdio>
#include<cmath>
using namespace std;

int main(){
    double approxAns = 1;
    double add = 2;
    double correctAns = exp(2);
    long long factorial = 1;
    printf("Iter no 1: Approx value: %lf; Exact Value: %lf ", approxAns, correctAns);
    int i=2;
    while(true){
        approxAns = approxAns + add/factorial;
        printf("Iter no %d: Approx value: %lf; Exact Value: %lf ", i, approxAns, correctAns);
        add = add * 2;
        factorial = factorial * i;
        if(correctAns-approxAns < 0.01){
            break;
        }
    i++;
    }
    printf("Final value: %lf ", approxAns);
    return 0;
}