【发布时间】:2012-02-13 11:38:36
【问题描述】:
以下程序冻结,我不知道为什么。
import java.math.*;
public class BigDec {
public static BigDecimal exp(double z) {
// Find e^z = e^intPart * e^fracPart.
return new BigDecimal(Math.E).pow((int)z, MathContext.DECIMAL128).
multiply(new BigDecimal(Math.exp(z-(int)z)), MathContext.DECIMAL128);
}
public static void main(String[] args) {
// This works OK:
BigDecimal x = new BigDecimal(3E200);
System.out.println("x=" + x);
System.out.println("x.movePointRight(1)=" + x.movePointRight(1));
// This does not:
x = exp(123456789);
System.out.println("x=" + x);
System.out.println("x.movePointRight(1)=" + x.movePointRight(1)); //hangs
}
}
对于目前的目的,第一种方法只是创建一个非常大的 BigDecimal。 (详细信息:它找到 e 的 z 次方,即使它太大而不能成为双精度数。我很确定这种方法是正确的,尽管 MathContexts 可能不在最佳位置。)
我知道 e^123456789 非常大,但我真的很想使用这样的数字。任何答案都将非常感激。
【问题讨论】:
标签: java bigdecimal