I'm trying to calculate Euler's number to a high degree of accuracy using BigDecimals but after a while, the numbers get so small that the JVM throws a divide-by-0 error. Any ideas on how to overcome? I find that the try-catch block is always called after exactly 34 iterations of the division, but I don't know why. The formula for Euler's number is an infinite series, so 34 iterations gets it close to the actual value of e, but not as accurate as I'd like it. It's not actually dividing by 0, but it's probably too small for the JVM to tell the difference.
BigDecimal ee = BigDecimal.ZERO;
for (int k = 0; k < 50; k++) {
int fact = factorial(k);
try {
BigDecimal trial = BigDecimal.ONE.divide(BigDecimal.valueOf(fact), 100, RoundingMode.CEILING);
} catch (Exception e) {
System.out.println("---- Div-by-0 error; Iterated " + k + " times ----");
break;
}
ee = ee.add(BigDecimal.ONE.divide(BigDecimal.valueOf(fact), 100, RoundingMode.CEILING));
}
System.out.println("\n---- Final: \t\te = " + power(ee, x));
}