Problem 2. Write computer programs to calculate e using the following two algori
ID: 3586695 • Letter: P
Question
Problem 2. Write computer programs to calculate e using the following two algorithms 2! 3! n! where the number of terms n necessary in order to maintain a given accuracy is dependent of the value of x. Here n is determined by requiring that the magnitude of the first ncglected tcrm in thc Taylor scries to bc smallcr than =10. You nccd to design your summation algorithm such that there is no overflow in computing the intermediate valucs. Thc cxact solution can bc obtaincd by using thc intrinsic math function. Print out your results ofex for x=-05,-5, -10, -20, -40. For every x, print the computed valuc ofe', exact value, relative error, and n used in computing the sum. Discuss and explain the differences in accuracy in the results by using the two algorithmsExplanation / Answer
Please save the below code in a cpp file and compile. You can modify the code as required. Result is based on term n (within the computation range long double)
/*********************************/
/*
* Exponential.cpp
*
* Created on: 05-Oct-2017
* Author:
*/
#include <iostream>
#include <stdlib.h>
#include <math.h>
using namespace std;
unsigned long long fact(int n);
int main()
{
long double result=0;
int n,choice;
double x;
cout<<"Enter no of terms you want ";
cin>>n;
cout<<"Enter value of x ";
cin>>x;
cout<<"Enter your choice: "
":1 for method 1"
":2 for method 2"<<endl;
cin>>choice;
switch(choice)
{
case 1:
for(int i=0;i<=n;i++)
{
result=result + pow(x,n)/(double)fact(i);
}
break;
case 2:
for(int i=0;i<=n;i++)
{
result=result + pow(-1,i)*pow(x,n)/(double)fact(i);
}
result=1.0/result;
break;
}
cout<<"result "<<result<<endl;
return 0;
}
unsigned long long fact(int n)
{
if(n<=1)
{
return 1;
}
return n*fact(n-1);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.