liveBook · Manning

Nan

As explained in Rust in Action: Systems programming concepts and techniques

Not a number is a floating-point special value representing an undefined or unrepresentable numeric result.

NaN means “Not a Number.” It is a special floating-point value for a mathematically undefined or otherwise invalid numeric result. For example, taking the square root of −42 or dividing 0 by 0 produces a NaN value. section 2.3.3 section 5.4.4

NaN can spread through a calculation: almost all operations involving it return NaN. It also defeats an ordinary equality check. A NaN value does not equal any value, including itself—even when two values have identical bit patterns. In Rust, an assertion that a NaN equals itself therefore fails. section 2.3.3 section 5.4.4

fn main() {
  let x = (-42.0_f32).sqrt();
  assert_eq!(x, x);
}

Run this short Rust example to see why checking a result against itself does not establish that it is a valid number. section 2.3.3

Check a suspect result with `is_nan()`. Use `is_finite()` when infinity should also be rejected. An assertion can then stop the program near the calculation that went wrong rather than letting an invalid result pass unnoticed. Infinity is a separate special value: dividing `1.0` by `0.0` demonstrates a failed `is_finite()` check, not a NaN. section 2.3.3

At the bit level, an `f32` whose exponent bits are all ones represents infinity, negative infinity, or NaN. Many distinct `f32` bit patterns represent NaN—approximately 4.2 million—so identical bits are not required for two values to share this behavior. section 5.4.4

How Rust in Action: Systems programming concepts and techniques covers it

How deep it goes
Explains comparison and propagation behavior, then locates NaN among exponent-bit special cases without decoding its individual bit patterns.
Examples
Uses the square root of −42, division of 0 by 0, self-equality assertions, and an infinity check.
What it assumes
Assumes basic numeric operations and comparisons while introducing NaN behavior without requiring bit-level decoding.
What you can do after
Diagnose/debug with it by checking suspect results using `is_nan()` or asserting `is_finite()` near a calculation.
How it connects
Connects NaN to floating-point comparisons, infinity, exponent bits, and subnormal numbers.

Also explained in

Compare how 9 books explain nan →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Rust in Action: Systems programming concepts and techniques. The section links point to the parts of the book it draws on.