-3

Is it possible to calculate Euler Number in 1000 iteration in one method and do I need to calculate factorial in the first place?

Here is my code:

import java.math.BigDecimal;

public class EulerNumber {

    public static void main(String[] args) {
        for (int i = 1; i < 1000; i++) { 
        }
        System.out.println("e = " + e);
    }

    private static double Euler() {
        return 0;
    }
}
TheBackalley
  • 11
  • 1
  • 2
  • 4
    Please remove all superfluous empty lines from your code and make sure its indention is consistent! Also, Your question is pretty easy to answer: Yes, it is. I don't think this is the answer you were after – so please make your question more precise!" – Marcus Müller Aug 21 '16 at 17:20

2 Answers2

2

It is pretty straight forward, if I understand it correctly, you need to calculate euler number in 1000 iteration, not calculating it 1000 times, so the for loop should be moved into Euler function.

public class EulerNumber {

    public static void main(String[] args) {
        System.out.println("e = " + Euler());
    }

    private static double Euler() {
        double e=1;
        double f=1;
        for ( int i=1; i <= 1000; i++) {
            f = f * (1.0 / i);
            if ( f == 0 ) break;
            e +=  f;
        }
        return e;
    }
}

e is the estimated euler number so far and f is the fraction to add in the next operation (1/n!). You don't have to calculate the n! each time, it is better to calculate it as you go on. I have checked and know that 1000 is too high for double precision, since f converge to 0 after 178 iteration in my computer. so the rest of process is not necessary.

1

Yes, it is possible to compute an approximation with over 2300 correct digits with a partial sum of 1000 terms. The error is smaller than 2/1000! (in magnitude 1/300^1000)

No, it is not necessary to compute the factorial, and in any case, one should avoid an explicit factorial function, just update the next term from the previous or use a Horner like scheme starting from the last term.

Lutz Lehmann
  • 25,219
  • 2
  • 22
  • 51