在1.7976931348623157E308(Double.MAX_VALUE)下的参数解决方案,但支持数百万的结果:
由于double支持的数字高达MAX_VALUE(例如,100!在double中看起来像这样:9.332621544394415E157),使用BigDecimal.doubleValue()没有问题。但是你不应该只做Math.pow(double,double),因为如果结果大于MAX_VALUE,你将会变得无穷大。 SO:使用公式X ^(AB)= X ^ A * X ^ B将计算分为两个幂,大,使用BigDecimal.pow和小(第二个参数的剩余部分),使用Math.pow,然后乘以。 X将被复制到DOUBLE – 确保它不大于MAX_VALUE,A将为INT(最大为2147483647但BigDecimal.pow不支持超过十亿的整数),B将为双倍,始终小于1。这样你可以执行以下操作(忽略我的私有常量等):
int signOf2 = n2.signum();
try {
// Perform X^(A+B)=X^A*X^B (B = remainder)
double dn1 = n1.doubleValue();
// Compare the same row of digits according to context
if (!CalculatorUtils.isEqual(n1, dn1))
throw new Exception(); // Cannot convert n1 to double
n2 = n2.multiply(new BigDecimal(signOf2)); // n2 is now positive
BigDecimal remainderOf2 = n2.remainder(BigDecimal.ONE);
BigDecimal n2IntPart = n2.subtract(remainderOf2);
// Calculate big part of the power using context -
// bigger range and performance but lower accuracy
BigDecimal intPow = n1.pow(n2IntPart.intValueExact(),
CalculatorConstants.DEFAULT_CONTEXT);
BigDecimal doublePow =
new BigDecimal(Math.pow(dn1, remainderOf2.doubleValue()));
result = intPow.multiply(doublePow);
} catch (Exception e) {
if (e instanceof CalculatorException)
throw (CalculatorException) e;
throw new CalculatorException(
CalculatorConstants.Errors.UNSUPPORTED_NUMBER_ +
"power!");
}
// Fix negative power
if (signOf2 == -1)
result = BigDecimal.ONE.divide(result, CalculatorConstants.BIG_SCALE,
RoundingMode.HALF_UP);
结果示例:
50!^10! = 12.50911317862076252364259*10^233996181
50!^0.06 = 7395.788659356498101260513