I have managed ( I think ) to get factorial and e calculated ok, but when I try and calcuate e^x it is wrong. Using a calculator e^5 is 148.413 but using my code it is 91.4167.
However it reurns 120 fro factorial 5 and calculates e as 2.71667 which is pretty close.
Clearly I'm missing something obvious but I can't see it...?
Thanks for your help.
// 4.34 (Factorial) The factorial of a nonnegative integer n is written n! (pronounced “n factorial”) and is defined as follows:
// n!=n·(n–1)·(n–2)·...·1 (for values of n greaterthan 1) and
// n!=1 (for n=0 or n=1).
// For example, 5! = 5 · 4 · 3 · 2 · 1, which is 120. Use while statements in each of the following:
// a) Write a program that reads a nonnegative integer and computes and prints its factorial.
// b) Writeaprogramthatestimatesthevalueofthemathematicalconstantebyusingthe
// formula:
// 1 1 1
// e = 1+--+--+--+...
// 1! 2! 3!
// Prompt the user for the desired accuracy of e (i.e., the number of terms in the summa-
// tion).
// c) Write a program that computes the value of e^x by using the formula
// 1! 2! 3!
//
// x x^2 x^3
// e^x = 1+--+--+--+...
// 1! 2! 3!
// Prompt the user for the desired accuracy of e (i.e., the number of terms in the summation).
#include<iostream>
#include<cmath>
usingnamespace std;
int main()
{
int counter = 0;
float e = 1, factorial = 1, eToThex = 1;
cout << "Input a number to compute its factorial: ";
cin >> counter;
while ( ! cin )
{
cin.clear();
cin.ignore();
cout << "Input a number to compute its factorial: ";
cin >> counter;
}
int power = counter;
for ( int i = 1; i <= counter; i++)
{
factorial *= i;
cout << factorial;
e += 1 / factorial;
eToThex += ((pow(power,i)) / factorial);
cout << "\t" << "i is: " << i;
cout << "\t\t" << "e to the x is: " << eToThex;
cout << "\tPower is: " << power << endl;
}
cout << "Factorial is: " << factorial << endl;
cout << "e is: " << e << endl;
cout << "e to the x is: " << 1 + eToThex << endl;
return 0;
}
The error of the approximation depends on the derivative of the function and the evaluation point. (see: Taylor Series)
You are quite far of the centre, and d(exp(x)/dx = exp(x) which grows quite fast.
Also, you misunderstood the assignment
Prompt the user for the desired accuracy of e (i.e., the number of terms in the summation).
you need two inputs:
- `x' the value for which you'll compute the approximation to e^x (should be close to 0, the centre of the series)
- `n' the number of terms of the approximation
Also, it seems to go against the spirit of the assignment to use the pow() function. After all, if you use that, you could simply use it to calculate the result directly. It becomes more interesting (and in my opinion more satisfying) if no functions from the <cmath> header are used at all.
Thanks very much! I now get an accurate series for e^x. As you pointed out I misunderstood the question.
My program now asks for the x to raise e to and then asks for the number of terms to be used in the approximation.