Search code examples
javafor-loopnested-loopseulers-number

Understanding why my for loop does not work to approximate e


e can be approximated using the formula e = 1 + (1/1!) + (1/2!) + (1/3!)... + (1/n!). I am trying to use for loops to accept whatever integer the user sets n to be. The program should approximate e by using the formula above from (1/1!) + .... (1/n!) and out put the result.

The nested for loop calculates the factorial of n (tested it separately and it works) and the variable defined, frac, puts the factorial into a fraction of 1/(answer to factorial). I store the value into a variable e and it should add the new fraction to the old value every time an iteration is done. I cannot not understand what is wrong with my loops that they are not out putting the right answer.

System.out.println("Enter an integer to show the result of 
approximating e using n number of terms.");
int n=scan.nextInt();
double e=1;
double result=1;
for(int i=1; n>=i; n=(n-1))
{
    for(int l=1; l<=n; l++)
            {
                result=result*l;
            }
    double frac=(1/result);
    e=e+frac;
}
System.out.println(e);

Output when I enter the integer 7 as n = 1.0001986906956286


Solution

  • You don't need that whole inner loop. All you need is result *= i.

    for (int i = 1; i <= n; i++)
    {
        result *= i;
        double frac = (1 / result);
        e += frac;
    }
    

    Here's a JavaScript version I just threw together:

    function init() {
      const elem = document.getElementById('eapprox');
    
      let eapprox = 1;
      const n = 15;
      let frac = 1;
    
      for (var i = 1; i <= n; ++i) {
        frac /= i;
        eapprox += frac;
      }
    
      elem.textContent = eapprox;
    }
    

    This yields 2.718281828458995. Plunker here: http://plnkr.co/edit/OgXbr36dKce21urHH1Ge?p=preview