Why do these simple double comparisons return true?
System.out.println(Double.MAX_VALUE == (Double.MAX_VALUE - 99 * Math.pow(10, 290)));
System.out.println(new Double(Double.MAX_VALUE).equals(new Double(Double.MAX_VALUE - 99 * Math.pow(10, 290))));
I know it's probably a IEEE 754 precision problem, but I can't figure out what the exact problem is here.
Very large floating point numbers are very imprecise. What you are seeing is rounding error.
We could demonstrate floating point in base-10 (scientific notation), say with 1 digit for the exponent and 4 digits for the base:
It follows that:
You can see that as the numbers get larger, we lose precision. Lots of it.
For kicks, you can test it:
We can determine that the gap between
Double.MAX_VALUEand the next smallest value (called an ULP) is somewhere around10^292, which is a very large gap.We can determine its exact value with the help of
Math#ulp:Which is about
1.99584*10^292, or2^971.