I am trying to make a program to approximate e by summing the following number series:
e = 1 + (1 / 1!) + (1 / 2!) + (1 / 3!) .... + (1 / i!)
Currently, my code looks like this:
public static void main(String[] args) {
BigDecimal one = new BigDecimal(1);
BigDecimal e = new BigDecimal(1.0);
BigDecimal divisor = new BigDecimal(1.0);
for (int i = 1; i <= 12; i++) {
divisor = divisor.multiply(new BigDecimal(i));
e = e.add(one.divide(divisor));
System.out.println("e = " + e);
}
}
The program performs the calculation (1 / n!) succesfully for n <= 2, but as soon as n >= 3 I get an error message. It seems like the program can't handle a divisor bigger than 2. The output of the program is:
e = 2
e = 2.5
Exception in thread "main" java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result. at java.math.BigDecimal.divide(Unknown Source) at ch10.Chapter_10_E20_ApproximateE.main(Chapter_10_E20_ApproximateE.java:16)
How should I use the BigDecimal class to preform a summation for e = 1 + (1 / 1!) + (1 / 2!) + (1 / 3!) .... + (1 / i!) ?