Some Java Modulo / Remainder Operator Issues

I play with some big values ​​with Java and I come across something that I don't understand. For some reason, Java seems to like giving me bum data (although, most likely, I am telling it to give me bum data).

Here's a snippet edited for clarity:

System.out.println( "2 == " + (Math.pow(51, 13) % (77)) ); 

Which, according to both Wolfram Alpha (see link below), and the rest of my algorithm is incorrect.

(Output:)

  2 == 70.0 

http://www.wolframalpha.com/input/?i=51^13+mod+77

Any ideas?

+4
source share
2 answers

I find this because of the exact problem. double are accurate up to 15 digits. Math.pow(51,13) is a huge number (~ 20 digits), so when you try to modify it to 77, you will have numerical errors.

For arbitrary precision arithmetic, take a look at BigInteger and BigDecimal .

+7
source

This is definitely a double precision problem. Using java.math.BigInteger works:

 groovy:000> b = new BigInteger("51") ===> 51 groovy:000> b = b.pow(13) ===> 15791096563156692195651 groovy:000> b = b.remainder(77) ===> 2 
0
source

All Articles