Floating-Point Arithmetic & Number Representation

Inf and NaN

/ INF and NAN (rhymes with 'can') /

What should a computer return for 1.0/0.0, or for sqrt(-1.0), or for an overflowed result that is genuinely too big to store? Halting the whole program for each such event would be brutal. IEEE 754 instead reserves two kinds of special values to represent these outcomes gracefully: Inf, a signed infinity for results that are too large or are mathematical infinities, and NaN, 'Not a Number', for results that are genuinely undefined.

Inf comes as +Inf and -Inf and behaves like a sensible limit: 1.0/0.0 = +Inf, 1.0/(-0.0) = -Inf, Inf + 1 = Inf, and 1.0/Inf = 0. NaN is produced by truly indeterminate operations: 0.0/0.0, Inf - Inf, sqrt(-1.0), 0.0*Inf. Both are encoded using the reserved all-ones exponent pattern (the fraction is zero for Inf, nonzero for NaN). Their defining feature is PROPAGATION: almost any arithmetic operation involving a NaN returns a NaN, so a single undefined value flows downstream and contaminates everything it touches, which is actually useful — it flags that something went wrong rather than hiding it behind a plausible number.

NaN has one famously surprising rule: it is unequal to everything, including itself. The test (x != x) is true exactly when x is a NaN, and this is the standard, portable way to detect one. That rule also makes NaN a silent saboteur of comparisons and sorts: max(3, NaN) may return either operand depending on the library, and a NaN slipping into your data can make a 'sorted' array nonsensical or a convergence test never trigger. When debugging a numerical code that produces garbage, the first move is often to hunt for where the first NaN or Inf was born.

A stopping test written 'while (residual > tol)' will loop forever if residual ever becomes NaN, because NaN > tol is false AND NaN <= tol is false — comparisons with NaN are always false. Detect it explicitly with (residual != residual) or an isnan() check before trusting the loop's exit.

NaN != NaN — the standard trick to detect one.

Inf and NaN are features, not crashes: they let a computation continue and SIGNAL trouble instead of hiding it. But because every comparison with NaN is false, NaN can silently break loops, sorts and tests — never assume 'x >= 0 else x < 0' covers all cases.

Also called
infinity and not-a-numberInfinityNaN無窮與非數