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!) ?
As we all know, dividing by 3
yields a number with a decimal representation that continues forever.
0.5 / 3 = 0.166666666666666666666666666666666666666666666666666666666666666666....
That is like what is going on with your division internally in the BigDecimal
, except that int
s in binary form are being calculated.
You will need a different overload of divide
that takes a scale to use (number of decimal digits beyond the decimal point) and the rounding mode. This tells the BigDecimal
how many digits to use and how to round when it stops.
e = e.add(one.divide(divisor, 20, RoundingMode.HALF_EVEN));
Final estimate of e
outputted:
e = 2.71828182828616856395