It seems a very basic question, but I have been having this problem for a while.
I am coding a program in Eclipse IDE which calculates a high quantity of decimals of the Euler's number, and it works fine with quantities like 100, 400, 1000...
But when I want to print more than 1500 decimals, this is the output that I get:
It only prints "2.", I thought that was a problem of the algorithm, so, to check if my code was correct, I stored the output in the clipboard to see the result number, and it was calculating more than 1500 decimals without any error.
Anybody knows how can I print the number in the console without having this mistake?
Also I leave the code here to provide more details:
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.math.*;
import javax.tools.Tool;
public class eulersNumberCalculation {
public static void main(String args[]) {
// E NUMBER
BigDecimal eNumber = new BigDecimal("0"), precision = new BigDecimal("1500");
for (BigDecimal i = BigDecimal.valueOf(0); i.compareTo(precision) <= 0; i = i.add(BigDecimal.ONE)) {
BigDecimal res = BigDecimal.ONE.divide(factorial(i), new MathContext(100, RoundingMode.HALF_UP));
eNumber = eNumber.add(res);
}
System.out.print(eNumber.toString());
}
public static BigDecimal factorial(BigDecimal n) {
if (n.compareTo(BigDecimal.ZERO) == 0) {
return BigDecimal.ONE;
} else {
BigDecimal b = n;
b = b.subtract(BigDecimal.ONE);
BigDecimal resultado = n;
for (BigDecimal i = n; i.compareTo(new BigDecimal("1")) > 0; i = i.subtract(BigDecimal.ONE)) {
resultado = resultado.multiply(b);
b = b.subtract(new BigDecimal("1"));
}
return resultado;
}
}
}