Wrong result by Java Math.pow

Maxim Mayers picture Maxim Mayers · Mar 31, 2012 · Viewed 7.9k times · Source

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?

Answer

aroth picture aroth · Mar 31, 2012

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.