Skip to content
Tactiverge

School/△ Builder/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

1.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.

  • ◇ Explain why many decimal fractions cannot be stored exactly in binary.
  • ◇ Predict when floating-point error appears and how it accumulates in a loop.
  • ◇ Compare floats with a tolerance (math.isclose or abs(a − b) < tol) instead of ==.

2.Watch

→ 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.

Length: see YouTube · captions on YouTube · source

Nothing loads from YouTube until you press play.

The video is optional: everything you need is also in the lesson text and the interactive.

3.Predict

What does Python print for 0.1 + 0.2?

Guess first. Being wrong here is how the surprise works.

4.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?

Loading the interactive…

Can't use the interactive? Read a description instead

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.

5.Checkpoint: guided practice

Check what you just discovered before going on. Hints appear after a wrong answer.

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?

6.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

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.

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

  • 0.1 + 0.2 != 0.3 means Python has a bug.
    ✓ It is how binary floating point works in almost every language. Python is doing exactly what IEEE 754 specifies.
  • Floats are random or unreliable.
    ✓ Floats are deterministic and very accurate (about 16 significant digits). Only exact equality tests and long accumulations need care.

7.Practice on your own

Practice, not a test. Wrong answers get a hint and another try.

Practice 3 · a fresh version every time

A regulator should output 2.5 V. A test reads 2.502 V. What is the absolute error, |measured − expected|, in millivolts?

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?

8.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.

9.Reflect

10.Go further

Concepts: Variables, types and expressions