liveBook · Manning

FP32

As explained in 100 Go Mistakes and How to Avoid Them

float32 is Go's 32-bit floating-point type with an 8-bit exponent, a 23-bit mantissa, and a sign bit.

Treating float32 as exact real arithmetic causes surprising results. Go stores values approximately because infinitely many real numbers must fit into 32 bits. FP32 follows IEEE-754: one sign bit, an 8-bit exponent, and a 23-bit mantissa. section 3.3

A multiplication that loses digits

var n float32 = 1.0001 fmt.Println(n * n) The mathematical result is 1.00020001, but the stored FP32 approximation produces 1.0002 on most x86 processors. The value stored for 1.0001 is approximately 1.000100016593933, not the exact decimal. section 3.3

var n float32 = 1.0001
fmt.Println(n * n)

Run the minimal Go example to observe FP32 rounding directly. section 3.3

Keep these consequences in mind:

  • Floating-point arithmetic approximates real arithmetic, so precision can be lost. section 3.3
  • The representation uses the form sign × 2^exponent × mantissa; conversion internals are intentionally not developed further. section 3.3

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Defines FP32 representation and demonstrates rounding, but stops short of fully explaining decimal conversion.
Examples
Demonstrates 1.0001 multiplication and the stored approximation of 1.0001.
What it assumes
Assumes basic Go values and arithmetic while motivating floating point through integers' inability to represent fractions.
What you can do after
Diagnose small numerical discrepancies caused by FP32 representation and arithmetic.
How it connects
Links FP32 to floating-point arithmetic, IEEE-754, mantissas, exponents, and float64.

Also explained in

Compare how 3 books explain FP32 →

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.