Video in progress

Strong Middle ☕ Core Java

What traps are there with NaN, -0.0 and Double.compare() when working with double?

NaN == NaN is false, but Double.valueOf(NaN).equals(NaN) is true; 0.0 == -0.0 is true, but equals says false. == follows IEEE 754, while equals/compare look at the bits, and in collections and sorting that difference causes bugs.

📖 Answer

double nan = 0.0 / 0.0;
nan == nan;                                // false
Double.valueOf(nan).equals(nan);           // true
Double.compare(nan, 1.0);                  // 1: NaN is treated as the largest

0.0 == -0.0;                               // true
Double.valueOf(0.0).equals(-0.0);          // false
Double.compare(0.0, -0.0);                 // 1

Why: the primitive == follows IEEE 754. equals and hashCode compare the bits through doubleToLongBits, otherwise you could add a NaN to a HashSet and never find it again.

Where it lets you down:

  • Writing your own compareTo as a < b ? -1 : a > b ? 1 : 0: transitivity breaks wherever there's a NaN, and TimSort can throw "Comparison method violates its general contract!". Always use Double.compare.
  • A double component in a record: equals works with Double.compare semantics, so new P(0.0).equals(new P(-0.0)) is false.
  • If a NaN appears in a calculation, it "poisons" all the following operations and silently ends up in the DB or in JSON (Jackson writes it as the string "NaN" by default, so a client expecting a number fails, and standard JSON has no NaN number at all). Check with Double.isNaN / isFinite at the boundaries.