BackendBench
Coffee
Spot the Bug #71

NaN is not equal to itself

A hard Java puzzle in the floating point and money family. One line below contains a real bug. Try to spot it first, then read why it fails and how to fix it.

hardFloating point and moneybuggy line: 10

Highlighted: line 10. Play this one as a puzzle without the answer.

What is wrong

Any comparison with NaN using == is false, including NaN == NaN. The empty array produces 0.0 / 0, which is NaN, but the check never matches and the program prints "average NaN".

The fix

if (Double.isNaN(avg)) {

How to avoid it next time

Use Double.isNaN. Better, guard against the empty input before dividing.

Want the background? Read Primitive types and floating point in the Java concepts library.

About floating point and money

Binary floating point cannot represent most decimal fractions exactly, so equality checks and money calculations with double drift. BigDecimal needs its own care: construct it from strings and always give a scale and rounding mode.

In code review: Flag double or float used for currency, and any == or != on floating point. Check how BigDecimal values are created and rounded.

More puzzles in this family

๐Ÿž Play today's puzzleAll 132 bugsโ† #70#72 โ†’

Frequently asked questions

What is the bug in "NaN is not equal to itself"?

Any comparison with NaN using == is false, including NaN == NaN. The empty array produces 0.0 / 0, which is NaN, but the check never matches and the program prints "average NaN". The faulty line is line 10: if (avg == Double.NaN) {

How do I fix it?

Replace it with: if (Double.isNaN(avg)) {. Use Double.isNaN. Better, guard against the empty input before dividing.

How do I catch floating point and money in code review?

Flag double or float used for currency, and any == or != on floating point. Check how BigDecimal values are created and rounded.

Is there a new puzzle every day?

Yes. The daily Spot the Bug puzzle picks one of these snippets for each UTC day, with the difficulty set by the weekday. Your streak is stored only in your browser.

More tools you might need