Search code examples
javaeulers-number

Issue finding euler's number in java


i have to find e, which is 1/0! + 1/1! + 1/2! + 1/3!... + 1/n! given n as a parameter and i'm having trouble getting the correct answer.

public double Factorial(int n) {
        long fact = 1;
        for (int i = 1; i <= n; ++i) {
            fact *= i;
        }
        return fact;
    }



    public double euler(int n) {
        double y = 0;
        for (int x = 0; x <= n; x++) {
            double e = 1 / Factorial(n);
            y = y + e;
        }
        return y;

when i input 10, this outputs 2.7557319223985893E-6 when i should be getting 2.7182818011463845. i ran through the code a few times but i can't figure out the issue. any help is appreciated.


Solution

  • The answer given in the comments addresses the problem. And since you have the algorithm down you may be interested in the following:

    A factorial method is not necessary. Since each subsequent value of n! is n! * (n+1) you can work it into your main loop as follows.

    // initialize fact to 0!
    double fact = 1;
    
    // first Euler term 1/0!
    double y = fact;
    
    for (int x = 1; x <= n; x++) {
        // next factorial
        fact *= x;
        // subsequent terms
        y += (1 / fact);
    }
    System.out.println(y);
    

    Prints

    2.7182818011463845
    

    And Euler's number is also the limit of (1 + r)(1/r) as r approaches 0.

    double r = .000000001;
    System.out.println(Math.pow(1 + r, 1/r));
            
    2.71828205201156