0

I came around a very strange issue when trying to find the 2^64 in java and in python. In java, 2^64 is producing output 18446744073709552000.000000 ~ while in python its producing 18446744073709551616.

And the correct answer is the one that is produced by python script. i.e. 18446744073709551616

Can someone help me to understand this weird behaviour?

Python:

print(pow(2,64)); //18446744073709551616

Java:

System.out.printf("%f",Math.pow(2,64)); //8446744073709552000.000000
AsSiDe
  • 1,826
  • 2
  • 15
  • 24
  • 1
    [`Math.pow`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Math.html#pow(double,double)) in Java uses double, which means it is a floating point. If you need to be exact look at `BigInteger` instead. – Mark Rotteveel Feb 17 '20 at 13:52
  • 1
    in addition to @MarkRotteveel's comment: floating points become very imprecise the higher the value. – Tobias Brösamle Feb 17 '20 at 13:54
  • @MarkRotteveel Thanks for pointing out the Double return by Math.pow(). I've used this BigInteger and BigDecimal before but not aware of broken floating point calcuations in java. – AsSiDe Feb 17 '20 at 14:02
  • @MarkRotteveel +2 – AsSiDe Feb 17 '20 at 14:03
  • 1
    Be aware, in Java, float is a different type than double (float is 32 bit floating point, double is 64 bit floating point). And there is nothing "broken" about floating point calculations, and this is not specific to Java: it happens for all calculations with floating point numbers in all languages. – Mark Rotteveel Feb 17 '20 at 14:03
  • @MarkRotteveel Just corrected my comment regarding Float and Double. Thanks again for clear this out that it's not related to programming languages. Just checked in Google's BigQuery its POW(2,64) is producing the same output as java i.e. `8446744073709552000` – AsSiDe Feb 17 '20 at 14:12

0 Answers0