liveBook · Manning

Nan

As explained in 100 Go Mistakes and How to Avoid Them

NaN is the IEEE-754 floating-point value representing an undefined or unrepresentable numerical result.

A common mistake is treating NaN like an ordinary number. NaN (Not-a-Number) represents an undefined or unrepresentable floating-point result. Under IEEE-754, it is the only floating-point value for which f != f. section 3.3

Constructing special floating-point values

A zero-valued float64 can produce positive infinity, negative infinity, and NaN: var a float64 positiveInf := 1 / a negativeInf := -1 / a nan := a / a fmt.Println(positiveInf, negativeInf, nan) // +Inf -Inf NaN section 3.3

var a float64
positiveInf := 1 / a
negativeInf := -1 / a
nan := a / a
fmt.Println(positiveInf, negativeInf, nan)
+Inf -Inf NaN

Constructs positive infinity, negative infinity, and NaN from float64 arithmetic. section 3.3

Use the value’s special behavior when diagnosing results:

  • Check for NaN with math.IsNaN rather than relying on ordinary equality. section 3.3
  • Treat NaN as evidence that an earlier floating-point operation was undefined or unrepresentable. section 3.3

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Defines NaN, demonstrates its construction, and gives its IEEE-754 comparison property and math.IsNaN detection.
Examples
Uses zero-valued float64 division to produce positive infinity, negative infinity, and NaN.
What it assumes
Assumes familiarity with Go floating-point variables and basic arithmetic while identifying IEEE-754 special values.
What you can do after
Diagnose floating-point results with math.IsNaN and recognize why equality testing cannot identify NaN.
How it connects
Connects NaN to IEEE-754, floating-point numbers, floating-point calculations, and positive and negative infinity.

Also explained in

Compare how 9 books explain nan →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.