Data Representation & Number Systems

not a number (NaN)

/ nan /

NaN, short for 'not a number', is a special floating-point value that means 'the result of this calculation is not a valid number'. When an operation has no sensible numeric answer — like 0.0 divided by 0.0, or the square root of a negative number, or infinity minus infinity — IEEE 754 does not crash the program; it produces NaN, a kind of error flag that lives inside the number system itself. Think of it as the floating-point equivalent of a calculator showing 'Error' but letting you keep going.

NaN has one famously strange property that is deliberate, not a bug: it is not equal to anything, including itself. The comparison NaN equals NaN evaluates to false. This is actually the cleanest way to test for it: a value is NaN exactly when it is not equal to itself, so 'x is not equal to x' is the classic NaN check. NaN is also contagious — almost any arithmetic that touches a NaN produces NaN — so once one appears, it tends to spread through a computation and poison the final answer, which is helpful because it makes the problem visible rather than silently wrong. (Floating point also has signed infinities, positive and negative, for results that overflow the range, like 1.0 divided by 0.0; infinity is a valid value, NaN is the 'no valid value' marker.)

Why this matters: NaN appearing in your output is a signal that something undefined happened upstream — a missing data value, a bad division, a domain error — and chasing where the first NaN came from is a routine debugging task. The honest pitfall to remember is that NaN breaks the usual rules of comparison: sorting, equality tests, and 'find the maximum' logic can all behave surprisingly when NaN is present, so code that handles real measured data should check for it explicitly.

Computing 0.0 / 0.0 gives NaN, not zero and not infinity. Then the test (NaN == NaN) returns false — so the idiom to detect a NaN is to check whether a value is not equal to itself: x != x is true exactly when x is NaN.

NaN marks an undefined result and is never equal to itself, even NaN == NaN is false.

NaN is not equal to itself, so equality tests, sorting, and max/min can misbehave when it appears. It is also contagious: most arithmetic touching a NaN yields NaN, which usefully makes the error visible.

Also called
NaN非數字