分数在java中怎么定义_如何在Java中对BigDecimal进行分数上电?

在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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值