Calculating Euler's number e with BigDecimal
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
public class Main {
final static int LASTITER = 17;
public static void main(String[] args) {
MathContext mc = new MathContext(100, RoundingMode.HALF_UP);
BigDecimal result = BigDecimal.ZERO;
for (int i = 0; i <= LASTITER; i++) {
BigDecimal factorial = factorial(new BigDecimal(i));
BigDecimal res = BigDecimal.ONE.divide(factorial, mc);
result = result.add(res);
}
System.out.println(result);
}
public static BigDecimal factorial(BigDecimal n) {
if (n.equals(BigDecimal.ZERO))
return BigDecimal.ONE;
else
return n.multiply(factorial(n.subtract(BigDecimal.ONE)));
}
}
Home
Java Book
Essential Classes
Java Book
Essential Classes
BigDecimal:
- BigDecimal class
- Constants for One, Ten and Zero
- Rounding mode
- Create BigDecimals
- Methods used to do calculation
- Convert BigDecimal to primitive data types
- Compare two BigDecimal
- Move decimal point
- Scale and precision
- Convert BigDecimal to String
- Remove the trailing zeros
- Convert double and long to BigDecimal
- Calculating Euler's number e with BigDecimal