I have an assignment where we are told to estimate the value of e using the formula e= 1 + 1/1! + 1/2! + 1/3!...
my code runs but, I can't seem to get the right decimal value for e. I can't identify what I am doing wrong. Is it the way I initiated my variables?? Any help is appreciated.
#include <iostream>
#include <iomanip>
using namespace std;
#include <iostream>
#include <iomanip>
int main()
{
double expo = 1, term = 1 ;
int counter = 1 ;
while( term > 1.0e-16 ) // while term is not close to zero
{
expo += term ;
term /= ++counter ;
}
std::cout << "The estimated value of e is "
<< std::fixed << std::setprecision(12) << expo << '\n'
<< "The actual value of e is 2.7182818284590452353602874...\n" ;
}
#include <iostream>
#include <iomanip>
usingnamespace std;
constdouble e_actual = 2.7182818284590452353602874;
int main()
{
// factorial now declared within while loop
//double expo = 1, factorial = 1, counter = 0;
double expo = 1, counter = 0;
while (counter <=15)
{
counter = counter + 1;
int x1 = counter; // double not right here
double factorial = 1; // <== always start from 1
while (x1 > 1)
{
factorial = factorial*x1;
x1 = x1 - 1;
}
expo = expo + (1/factorial);
}
cout << setprecision(8); // only need to set this once
cout << "The estimated value of e is " <<expo << endl;
cout << "Whereas its actual value is " << e_actual << endl;
return 0;
}
Now, clicking on the little cogwheel and running, I get:
The estimated value of e is 2.7182818
Whereas its actual value is 2.7182818
But, as JLBorges code shows you, you are doing more work than necessary recalculating the factorial each time. And slowing your program right down, too.
Andy
PS Code reads better when displayed using code tags!