โ† Back

Home โ€บ Output practice โ€บ floats are not exact

Predict the output: floats are not exact

๐Ÿ”ฎ Predict the outputTopic: numbersDifficulty: mediumNo login needed

The snippet

Nothing is broken in Python. 0.1 cannot be written in base 2, the way 1/3 cannot be written in base 10 โ€” the computer stores the closest binary fraction and every later digit you see is the error of that approximation.

print(0.1 + 0.2)
print(0.1 + 0.2 == 0.3)
print(round(2.675, 2))

Your prediction

Type exactly what this program prints โ€” one line per print() call:

The output

0.30000000000000004
False
2.67

Verified against CPython 3.11 in this repo's build

Line-by-line explanation

  1. print(0.1 + 0.2)
    The stored sum is the float nearest to 0.3, which prints with all the digits needed to identify it โ†’ 0.30000000000000004.
  2. print(0.1 + 0.2 == 0.3)
    0.3 on its own is a *different* nearby float, so the comparison is False. That is why money code never uses == on floats.
  3. print(round(2.675, 2))
    2.675 is really 2.67499999999999982โ€ฆ in binary, and round is correct about *that* number โ†’ 2.67, not 2.68.
  4. (fix)
    round(0.1 + 0.2, 2) == 0.3 is True; for exactness use decimal.Decimal("2.675") or work in integer paise/cents.

The rule you can reuse

Compare floats with a tolerance (math.isclose(a, b)) or Decimal for money, and remember round() is *banker's rounding*: it breaks ties to the even digit.

Why most predictions break here

Writing True for the equality and 2.68 for the round. Both come from assuming the decimal literal is what gets stored.

Quick fire

Same rule, two more shapes. Predict first, then open.

Predict this too
print(0.5 + 0.25 == 0.75)
print(round(0.5), round(1.5), round(2.5))

Output
True
0 2 2

Halves and quarters are exact in binary โ†’ True; ties round to even โ†’ 0 2 2.

Predict this too
print(0.1 + 0.1 + 0.1 == 0.3)
print(sum([0.1] * 10) == 1.0)

Output
False
False

Accumulated error: the first is False, and the ten-sum lands on 0.9999999999999999 โ†’ False False.

Share your result

Challenge a friend โ€” the link contains the question, never the answer:

Copied โœ“

Keep practising this rule

More output questions โ†’ All interactive problems

Questions this page answers

Is this a Python bug?

No โ€” it is IEEE-754 binary floating point, the same in JavaScript, C, Java and Excel. 0.1 + 0.2 == 0.3 is False everywhere floats are binary.

How do I print money correctly?

Keep integer paise, or Decimal built from *strings* (Decimal("2.675"), never Decimal(2.675)), then quantise for display: f"{rupees:.2f}".