Invalid Java Math.pow result

If you try to run the following code

public class Main { public static void main(String[] args) { long a = (long)Math.pow(13, 15); System.out.println(a + " " + a%13); } } 

You will receive "51185893014090752 8"

The correct value is 13 ^ 15 51185893014090757 , that is, 5 more than the result returned by Math.pow . Any ideas on what might cause this?

+9
java math long-integer pow
Mar 31 2018-12-12T00:
source share
6 answers

You have exceeded the number of significant digits available (from 15 to 16) in double precision floating point values. Once you do this, you cannot expect the least significant numbers of your result to be truly meaningful / accurate.

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

+7
Mar 31 '12 at 13:59
source share

The problem is that as you reach higher double values, the gap between consecutive values ​​widens - a double cannot represent each integer value within its range, and what is going wrong here. It returns the closest double value to the exact result.

+5
Mar 31 '12 at 13:59
source share

This is not a problem of accuracy. The Math.pow method approximates 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 result is the expected result 51185893014090757L.

More generally, the use of the Math.pow method should be avoided when the exponent is an integer. Firstly, the result is approximate, and secondly, it is more expensive to calculate.

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

+4
Feb 18 '14 at 11:51
source share

The double has finite accuracy, its mantissa is 52 bits, which is approximately equal to 15-16 decimal places. Thus, the number you are trying to calculate cannot be represented (exactly) as a double.

+1
Mar 31 '12 at 13:59
source share

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

Have you checked if this is so or not?

0
Mar 31 '12 at 13:59
source share

this is because of the limit of holding digits in debt, if you use double, float you may be able to, but it will have some errors, you must handle the calculation digits yourself, storing them in an array, which is not an easy way

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

to be successful!!!

0
Mar 31 '12 at 15:33
source share



All Articles