0

When in Java I compare (1.0d == 1.0d - Double.MIN_VALUE), it returns true even though while very close in reality 1.0d should be greater than (1.0d - Double.MIN_VALUE).

If I use Double.compare(1.0d, 1.0d - Double.MIN_VALUE), it returns 0. Meaning those two values are equal.

When I print Double.doubleToLongBits(), the same value is printed for both 1.0 and 1.0d - Double.MIN_VALUE.

The same happens if I use Double.MIN_NORMAL too.

Why does this happen? What can I do to make the comparison return the proper result?

Thanks!

Abushawish
  • 1,466
  • 3
  • 20
  • 35
  • 1
    Aside from being a duplicate, please read [What Every Programmer Should Know About Floating-Point Arithmetic -or- Why don’t my numbers add up?](http://floating-point-gui.de/) because you're not working "numbers", you're working with very special bit patterns. – Mike 'Pomax' Kamermans Feb 21 '18 at 17:19
  • 4
    If you change the least significant bit of `1.0`, its value changes by about 2*10^-16. That's about 308 orders of magnitude bigger than `Double.MIN_VALUE` (about 5*10^-324). Doubles just don't have sufficient precision to represent that difference correctly. – Andy Turner Feb 21 '18 at 17:27
  • Thanks Andy, it seems like "0.000000000000001d" is the smallest double that can still change the value of "1.0d". Will it always be 0.000000000000001, or is that a fluke in my case or a fluke for only 1.0d? – Abushawish Feb 21 '18 at 19:39
  • It depends on the value. Use Math.ulp(d) to get the smallest value that can change d. – Louis Wasserman Feb 22 '18 at 06:53

0 Answers0