liveBook · Manning

Floating-point arithmetic

As explained in Learn Go with Pocket-Sized Projects

A floating-point number is a numeric value represented using a finite significand and an exponent, allowing a wide range of magnitudes with limited precision.

Floating-point numbers represent a wide range of magnitudes with limited precision. Go provides float32 and float64 under IEEE-754: float32 uses 4 bytes and about six guaranteed decimal digits, while float64 uses 8 bytes and 15. section 6.2.1

Treat floating-point results as approximations:

  • Most decimal fractions cannot be represented exactly; 0.625 is an exception because it combines inverses of powers of 2. section 6.2.1
  • float32(123_456_789) prints as 123456792, and float32(0.0123456789) prints as 0.0123456791. section 6.2.1
  • Adding or subtracting values with very different magnitudes can lose the smaller value; subtracting 1 from float32(100_000_000) leaves 100 million. section 6.2.3
  • Avoid == for approximate results; compare the difference against an appropriate precision range. section 6.2.3

Comparing a computed zero

math.Sin(math.Pi) returns 1.2246467991473515e-16 rather than exactly zero. A tolerance check such as math.Abs(math.Sin(math.Pi)-0) < math.Pow(10, -15) treats the result as indistinguishable from zero. section 6.2.3

fmt.Printf("%.8f", float32(1)/float32(41)*float32(41))

Run the expression to observe how intermediate float32 rounding can affect a result. section 6.2.1

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Explains IEEE-754 representation, decimal precision, rounding examples, magnitude loss, tolerance comparisons, and bounded-value validation.
Examples
Demonstrates float32 rounding, lost currency subtraction, sin(π), tolerance checking, and bounded currency amounts.
What you can do after
Diagnose precision loss in Go and compare computed values with tolerances instead of exact equality.
How it connects
Connects floating-point arithmetic to IEEE-754, numerical precision, equality comparison, trigonometric functions, currency conversion, and validation.

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 Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.