Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrong result by Java Math.pow

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 get "51185893014090752 8"

The correct value of 13^15 is 51185893014090757, i.e. greater than the result returned by Math.pow by 5. Any ideas of what may cause it?

like image 857
Maxim Mayers Avatar asked Mar 31 '12 13:03

Maxim Mayers


People also ask

Is math POW inefficient?

Math. pow is slow because it deals with an equation in the generic sense, using fractional powers to raise it to the given power. It's the lookup it has to go through when computing that takes more time. Simply multiplying numbers together is often faster, since native calls in Java are much more efficient.

What does POW () do in Java?

pow(double a, double b) returns the value of a raised to the power of b . It's a static method on Math class, which means you don't have to instantiate a Math instance to call it. The power of a number is the number of times the number is multiplied by itself.

What is the output of math POW?

pow() is used to calculate a number raise to the power of some other number. This function accepts two parameters and returns the value of first parameter raised to the second parameter. There are some special cases as listed below: If the second parameter is positive or negative zero then the result will be 1.0.


1 Answers

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.

like image 92
Pierre-Nicolas Mougel Avatar answered Sep 24 '22 12:09

Pierre-Nicolas Mougel