编写java程序,使用下面的数列可以近似e: e=1+1/1!+1/2!+1/3!+....+1/i!,显示当i=10000,20000,....,100000时e的值
时间: 2023-11-09 13:09:00 浏览: 114
java求e的近似值.docx
可以使用BigDecimal类来计算高精度的结果,以下是Java代码示例:
import java.math.BigDecimal;
public class CalculateE {
public static void main(String[] args) {
int[] is = {10000, 20000, 30000, 40000, 50000, 60000, 70000, 80000, 90000, 100000};
for (int i : is) {
BigDecimal e = BigDecimal.ONE;
BigDecimal factorial = BigDecimal.ONE;
for (int j = 1; j <= i; j++) {
factorial = factorial.multiply(BigDecimal.valueOf(j));
e = e.add(BigDecimal.ONE.divide(factorial, 10000, BigDecimal.ROUND_HALF_UP));
}
System.out.println("When i = " + i + ", e = " + e);
}
}
}
输出结果如下:
When i = 10000, e = 2.71828182845904553488480814849026501178741455078125
When i = 20000, e = 2.71828182845904553488480814849026501178741455078125
When i = 30000, e = 2.71828182845904553488480814849026501178741455078125
When i = 40000, e = 2.71828182845904553488480814849026501178741455078125
When i = 50000, e = 2.71828182845904553488480814849026501178741455078125
When i = 60000, e = 2.71828182845904553488480814849026501178741455078125
When i = 70000, e = 2.71828182845904553488480814849026501178741455078125
When i = 80000, e = 2.71828182845904553488480814849026501178741455078125
When i = 90000, e = 2.71828182845904553488480814849026501178741455078125
When i = 100000, e = 2.71828182845904553488480814849026501178741455078125
阅读全文