liveBook · Manning

Floating-point arithmetic

As explained in 100 Go Mistakes and How to Avoid Them

A floating-point number is a finite-precision representation of a real value that uses a significand and exponent and may approximate real arithmetic.

A common mistake is expecting floating-point calculations to match real arithmetic exactly. Go's float32 and float64 use finite precision, so fractional values may be approximated and lose precision. section 3.3

The surprising multiplication result

Multiplying 1.0001 by itself may print 1.0002 rather than the expected 1.00020001. In float32, 1.0001 is stored approximately as 1.000100016593933, so the calculation starts with a different value. section 3.3

Use these details to diagnose the result:

  • float32 allocates 8 exponent bits and 23 mantissa bits; float64 allocates 11 exponent bits and 52 mantissa bits, with one remaining sign bit. section 3.3
  • Accumulation order affects error: repeatedly adding 1.0001 to 10,000 produces different results from adding it to zero and adding 10,000 afterward. section 3.3

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Explains approximation, IEEE-754 fields, and accumulation effects, but stops short of fully explaining decimal conversion.
Examples
Uses 1.0001 multiplication, float32 representation, and differently ordered accumulation loops.
What you can do after
Evaluate floating-point results while accounting for approximation, representation limits, and operation order.
How it connects
Connects floating-point arithmetic with IEEE-754, mantissa, exponent, precision, and real arithmetic.

Also explained in

Compare how 20 books explain floating-point arithmetic →

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.