Binary Floating-Point Rounding

A floating-point value stores a finite binary approximation to many familiar decimal fractions.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Find the finite forms
  2. Inspect one simple sum
  3. Decide which fractions have a finite binary spelling
  4. Distinguish stored rounding from display rounding

Find the finite forms

One half and one eighth have finite binary expansions. One tenth has a factor of five in its reduced denominator, so its binary expansion repeats. Binary floating-point rounds it to a nearby representable value. Displaying a value as text may hide that small difference.

Inspect one simple sum

On typical Python systems using binary64, adding 0.1 and 0.2 gives an approximation displayed as 0.30000000000000004, distinct from the one stored for 0.3. Use tolerance-based comparisons for measured quantities or an explicit decimal representation for decimal arithmetic.[1]

Decide which fractions have a finite binary spelling

In base two, fractional positions represent halves, quarters, eighths, and so forth. Three eighths has a finite representation because it is a quarter plus an eighth. One tenth cannot be written as an integer divided by any power of two because its reduced denominator contains a factor of five. When finite floating-point precision stores that value, it selects a representable neighbor. Try the fraction one half by repeated addition and compare it with repeated addition of one tenth. The absolute error measures the eventual difference from the intended mathematical total.

Distinguish stored rounding from display rounding

A formatter normally writes enough characters for a useful display or a chosen precision. The displayed 0.1 need not be the exact decimal expansion of the stored approximation. This is why printing a short value does not establish exact arithmetic. If a quantity represents a decimal price and preserving its scale matters, parse the supplied text into an exact decimal representation or a specified count of minor units. For a measured physical quantity, use a tolerance chosen from the measurement and computation contract. See decimal amounts and tolerance comparisons for those two decisions.

References

  1. Python Software Foundation, Python Tutorial: Floating-Point Arithmetic ↩