liveBook · Manning

Nan

As explained in Clojure: The Essential Reference

NaN is a floating-point value representing an undefined or unrepresentable numeric result and having special comparison behavior.

NaN (“Not A Number”) represents an undefined or unrepresentable floating-point result. It was introduced by IEEE 754 and is available in Clojure as `Double/NaN`. Despite its name, `(number? Double/NaN)` returns `true`. section 5.8

Where NaN comes from

Floating-point operations such as `(/ 0. 0)`, `(/ ∞ ∞)`, `(* 0 ∞)`, and `(Math/sqrt -1)` produce NaN. Arithmetic can carry it onward: `(inc Double/NaN)` also returns NaN. section 5.8

NaN is an edge case for functions that depend on numeric ordering. If any argument to `max` or `min` is NaN, the result is NaN—even when the other arguments include infinity. Numeric equality is surprising too: `(== Double/NaN Double/NaN)` returns `false`. section 5.8

Comparison is not numeric equality

`(compare Double/NaN 1)`, `(compare 1 Double/NaN)`, and `(compare Double/NaN Double/NaN)` each return `0`. That does not make NaN equal to those values under `==`. It also makes sorting results worth checking: `(sort [3 2 Double/NaN 0])` yields `(0 2 3 NaN)`, while `(sort [2 3 Double/NaN 0])` yields `(2 3 NaN 0)`. section 5.8 section 6.4

The practical rule is to account for NaN before relying on an extreme value or a sorted order. `max` and `min` propagate it; `compare` can return zero for it and an ordinary number. section 5.8 section 6.4

How Clojure: The Essential Reference covers it

How deep it goes
Defines the value and works through arithmetic and comparison results, without descending into its bit representation.
Examples
Shows undefined arithmetic yielding NaN, self-comparison returning false, extrema propagating NaN, and differing sort results.
What it assumes
Assumes basic Clojure arithmetic and function calls while defining NaN and demonstrating its unusual behavior.
What you can do after
Diagnose/debug with it when NaN changes an extrema calculation or makes comparison-based sorting unreliable.
How it connects
Connects NaN to IEEE 754, floating-point arithmetic, infinity, numeric equality, max, min, compare, and sorting.

Also explained in

Compare how 9 books explain nan →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.