BigDecimal.movePointRight()挂起的数字非常大



下面的程序冻结了,我不知道为什么。

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非常大,但我确实想使用这样的数字。如有任何答复,我们将不胜感激。

事实上,它并没有冻结,但在Oracle的VM中实现movePointRight可能效率极低。与使用movePointRightmovePointLeft方法相比,用10的幂进行乘法或除法通常要快得多。在您的情况下,使用x.multiply(BigDecimal.TEN)可能会更好。

最新更新