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.

 

 

猜你喜欢

转载自wooce.iteye.com/blog/2332282