Search code examples
c++matheulers-number

Calculating Euler's Number in C++


Write a program that calculates Euler’s number e. To do this, first write a function that takes a parameter n, and returns the result (1+1/n)n. The limit of this function approaches e as n approaches infinity. In your main program, write a loop that calls this function with increasing values of n. On each iteration, multiply n by 2 (if you just add 1 to n each time, the algorithm won' work) and stop when the your new approximation and your previous approximation differ by less than 1e-8. Now you have a pretty good estimate. So in main(), print your best approximation and the number n that generated it.

I have done everything up until the for-loop. I don't quite understand how am I supposed to stop for-loop after new and previous numbers are approximately the same.

Here is my function:

double euler_finder(double n)
{
    return pow((1+1/n), n);
}

And here is my for-loop in the main method, where ??? is where I'm having a problem:

for (int i=0; i<????; i*=2) {

}

EDIT: The solution has been posted so here how it looks like:

#include <iostream>
#include <iomanip>
#include <cmath>

using namespace std;

double euler(int n);

int main()
{
    int trialN = 4;

    double guess1, guess2;

    guess1 = euler(1);
    guess2 = euler(2);

    while(  abs(guess1-guess2) > 1e-8 )
    {
        cout<< trialN << " " << guess2<<endl;
        guess1 = guess2;
        guess2 = euler( trialN );
        trialN*=2;
    }

    cout<<setprecision(8)<<"e is approximately "<<guess2<<" and we got it with a value of ";
    cout<<trialN<<" for n";

    return 0;
}

double euler(int n)
{
    return pow((1+1.0/n), n);
}

Output:

4 2.25
8 2.44141
16 2.56578
32 2.63793
64 2.67699
128 2.69734
256 2.70774
512 2.71299
1024 2.71563
2048 2.71696
4096 2.71762
8192 2.71795
16384 2.71812
32768 2.7182
65536 2.71824
131072 2.71826
262144 2.71827
524288 2.71828
1048576 2.71828
2097152 2.71828
4194304 2.71828
8388608 2.71828
16777216 2.71828
33554432 2.71828
67108864 2.71828
134217728 2.71828
e is approximately 2.7182818 and we got it with a value of 268435456 for n

Solution

  • First of all, if i starts off at 0, and you keep multiplying by 2, it won't advance very far. Start off at 1.

    Second of all, according to the problem statement, you should stop when your approximation is good enough. So the loop stop condition is not on i, but rather abs(proper_E - your_approximation) > 1e-8