java的高精度大数字运算的问题

同事有以下高精度计算的java程序:

//计算 4/2^23*1000/6

                BigInteger bigInteger = new BigInteger("2");

                bigInteger = bigInteger.pow(23);

                BigDecimal b1 = new BigDecimal(4);

                b1 = b1.divide(new BigDecimal(bigInteger));

                Log.d("value:", b1 + "");

                b1 = b1.multiply(new BigDecimal(1000));

                Log.d("value:", b1 + "");

                b1 = b1.divide(new BigDecimal(6)); //在除6时报错

                Log.d("value:", b1 + "");

在执行b1 = b1.divide(new BigDecimal(6)); 这句时报错:

Exception in thread "main" java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.

同事问老杨, java的高精度浮点数都位数不够, 怎么办?

老杨建议,可以改用:

    b1 = b1.divide(new BigDecimal(6), , MathContext.DECIMAL128);

就可以了不会报错了。

其中位数可以按需要选择32, 64或128

可以参看:

http://edelstein.pebbles.cs.cmu.edu/jadeite/main.php?api=java6&state=class&package=java.math&class=MathContext

 

老杨附带指出对于以下程序,也一样会报上面的java.lang.ArithmeticException: Non-terminating decimal expansion;的错, 这是因为除法除不尽,java就不知道到底要几位存储,必须要指定precision和RoundingMode才行:

BigDecimal a = new BigDecimal(1);

BigDecimal b = new BigDecimal(3);

a.divide(b) ;

参看java5的描述(java8的文档参见http://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html):

When a MathContext object is supplied with a precision setting of 0 (for example, MathContext.UNLIMITED), arithmetic operations are exact, as are the arithmetic methods which take no MathContext object. (This is the only behavior that was supported in releases prior to 5.)

As a corollary of computing the exact result, the rounding mode setting of a MathContext object with a precision setting of 0 is not used and thus irrelevant. In the case of divide, the exact quotient could have an infinitely long decimal expansion; for example, 1 divided by 3.

If the quotient has a nonterminating decimal expansion and the operation is specified to return an exact result, an ArithmeticException is thrown. Otherwise, the exact result of the division is returned, as done for other operations.

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值