TactivergeLite

Lite / Building Machines That Respond / Week 3

Why 0.1 + 0.2 is not 0.3

Ask Python whether 0.1 + 0.2 == 0.3 and it says False. Is your computer broken?

About 35 min · 3 goals · Checked by automated tests · Full interactive version

Why should I care?

Every engineering program uses floats, and every float is a tiny bit approximate. Usually that doesn't matter. It matters a lot when code tests for exact equality, or adds a small step thousands of times. Knowing why stops a whole class of mysterious bugs.

Predict

What does Python print for 0.1 + 0.2?

  1. 0.3
  2. 0.30000000000000004
  3. 0.29999999999999999
Guess first, then reveal

0.30000000000000004. Neither 0.1 nor 0.2 can be stored exactly in binary, and their tiny errors add up to a value just above the float nearest to 0.3.

Discover

Add 0.1 one time, two times, three times… When does == first say False? Find a number of additions where == says True again. Then look at what Python really stores for 0.1, 0.5 and 0.25: which ones are exact?

What the interactive shows (text version)

The float explorer adds 0.1 to a total n times and prints the result as Python does: n = 1 gives 0.1, n = 2 gives 0.2, n = 3 gives 0.30000000000000004 (== 0.3 is False, math.isclose is True), n = 8 gives 0.7999999999999999. A second panel shows the exact stored values: 0.1 is 0.1000000000000000055511151231257827021181583404541015625, while 0.5 and 0.25 are exact.

You can also open the interactive on the full site when you have a faster connection.

Watch (optional)

Watch for: Listen for why some fractions repeat for ever in a given number base, and what the computer does when it runs out of digits.

Explains how computers store fractional numbers in binary, and why some simple decimals can only be stored approximately.

“Floating Point Numbers - Computerphile” by Computerphile (opens YouTube; streaming video uses a lot of data)

The video is optional. Everything you need is in this lesson's text.

Understand

See it in code

import math
total = 0.1 + 0.2
print(total)                       # 0.30000000000000004
print(total == 0.3)                # False
print(math.isclose(total, 0.3))    # True
print(abs(total - 0.3) < 1e-9)     # True

The last two lines are how engineers compare measured or computed values: within a stated tolerance.

Errors can accumulate

One addition is off by about 10⁻¹⁷. Add 0.1 a million times and the errors can add up to something you can see. A timer that does t = t + 0.1 every tick slowly drifts. The cure is to count whole ticks in an int and compute t = ticks * 0.1 when needed.

Practical rules

Never test floats with ==; use a tolerance that means something physically (1 mV, 0.01 °C). Keep money and counts in ints (pence, millimetres, ticks). Round only for display, with round() or an f-string such as f"{x:.2f}", not in the middle of a calculation.

Explain it another way

Intuitive

Try writing 1/3 as a decimal on a strip of paper with room for ten digits: 0.3333333333. It is close, but not exact. The computer has the same problem with 1/10, just in binary.

Technical

Python floats are IEEE 754 double precision: 1 sign bit, 11 exponent bits and a 52-bit fraction (53 significant bits). Each arithmetic operation is correctly rounded, so the relative error per operation is at most about 1.1 × 10⁻¹⁶.

Mathematical

A rational p/q (in lowest terms) has a terminating binary expansion only if q = 2ᵏ. For 1/10, q = 2 × 5, so the expansion is infinite and periodic, and the stored value differs from 0.1 by about 5.55 × 10⁻¹⁸.

Applied

Test code for sensors and simulations always compares within a tolerance, for example assert abs(measured_v - 3.3) < 0.005. Firmware on small chips often avoids floats entirely and stores millivolts or millimetres as integers.

Derivation: Why 0.1 cannot be written exactly in binary
  1. In base 10, 1/3 = 0.333… never ends, because 3 does not divide any power of 10. A fraction ends in base 10 only if its denominator is built from 2s and 5s (the factors of 10).

  2. In base 2, a fraction ends only if its denominator is a power of 2. 1/2 = 0.1₂ and 1/4 = 0.01₂ are exact, so 0.5 and 0.25 are stored perfectly.

  3. 0.1 = 1/10 = 1/(2 × 5). The factor 5 is not a power of 2, so in binary 0.1 repeats for ever: 0.000110011001100…₂.

  4. A Python float keeps 53 binary digits, so it stores the nearest value it can: 0.1000000000000000055511151231257827… That error is tiny (about 5.6 × 10⁻¹⁸) but not zero.

  5. 0.1 + 0.2 adds two rounded values and rounds again. The result lands one step above the float nearest to 0.3, so 0.1 + 0.2 == 0.3 is False while math.isclose(0.1 + 0.2, 0.3) is True.

Worked example 1

A test asserts led_resistor(3.3, 2.0, 10) == 130 and fails. The function returns 129.99999999999997. Is the function wrong?

No. (3.3 − 2.0) is stored as 1.2999999999999998, and dividing by 0.01 gives 129.99999999999997. The test is wrong: write assert abs(led_resistor(3.3, 2.0, 10) - 130) < 1e-9, or a tolerance that matches the resistor's own precision.

Common mix-ups

Practice

Practice, not a test. Answers are checked on our server; a wrong answer gets a hint and another try. Nothing is saved.

Practice 1. Which test is the right way to check that a computed voltage v is 3.3 V?
Practice 2. Which of these decimals is stored exactly as a Python float?

mV

Practice 4. What does print(0.1 * 3 == 0.3) show?
Practice 5. A timer adds 0.1 s every tick. What is the most reliable design?

Apply it

Write a program that adds 0.1 one thousand times in a float and also counts ticks in an int. Print both totals, their difference, and whether math.isclose says they match. Write one sentence on which you would trust in a timer.

Reflect

Where in a real machine would a tiny float error be harmless, and where could it matter?

Write your answer on paper or in your own notes. Lite never stores what you write.

Go further

← int, float, str and listTranslate a formula into Python →