TheBackalley - 2 months ago 23x

Java Question

Is it possible to calculate Euler Number in

`1000`

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;

}

}

Answer

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.

Source (Stackoverflow)

Comments