Wrong result by Java Math.pow

≯℡__Kan透↙ 提交于 2019-11-27 09:40:53

You've exceeded the number of significant digits available (~15 to 16) in double-precision floating-point values. Once you do that, you can't expect the least significant digit(s) of your result to actually be meaningful/precise.

If you need arbitrarily precise arithmetic in Java, consider using BigInteger and BigDecimal.

The problem is that as you get to higher and higher double values, the gap between consecutive values increases - a double can't represent every integer value within its range, and that's what's going wrong here. It's returning the closest double value to the exact result.

This is not a problem of precision. The Math.pow method performs an approximation of the result. To get the correct result use the following code.

long b = 13;
for(int i = 0; i != 14; i ++) {
    b = b * 13;
}
System.out.println(b);

The output is the expected result 51185893014090757L.

More generally, the Math.pow method usage should be avoided when the exponent is an integer. First, the result is an approximation, and second it is more costly to compute.

The implementation of Math.pow (and most other methods in the Math class) is based on the network library netlib as the package "Freely Distributable Math Library" (see StrictMath javadoc). The implementation in C is available at e_pow.c.

A double has finite precision, its mantissa is 52 bits, which roughly equals 15 to 16 decimals. So the number you're trying to calculate can't be represented (exactly) by a double any more.

The correct answer is to provide the closest number which can be represented by a double

Have you checked whether this is the case or not?

it is because of the limit of holding digits in long by casting to double, float you may be able but it will have some errors, you should yourself handle the digits of the calculation by saving them in an array that's not an easy way

but in python programming language you can have the result of any length, it is so powerful!

be successful!!!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!