Numbers that lie
Worked examples
Read the claim, then run it and check the machine agrees. One at a time — nothing here is taken on trust.
print(0.1 + 0.2) # not 0.3... print((0.1 + 0.2) == 0.3) # ...so this is a shock print(format(0.1, ".17f")) # the hidden 17th digit
Line 1 prints 0.30000000000000004 — the rounding error made visible.
Line 2 prints False: the stored sum differs from the stored 0.3 in
the last place, and == reports that honestly. Line 3 prints
0.10000000000000001 — proof that even a lone 0.1 was never exact;
Python just hides the tail when it prints normally.
import math
total = 0.0
for _ in range(10):
total = total + 0.1 # add a tenth, ten times
print(total) # should be 1.0 ... right?
print(total == 1.0) # the trap
print(math.isclose(total, 1.0)) # the honest question
The loop adds 0.1 ten times, so total should be 1.0. It prints
0.9999999999999999 — each add carried a speck of rounding and they
accumulated. total == 1.0 is therefore False. But
math.isclose(total, 1.0) is True: it asks "close enough, allowing
for float rounding?" and that is the question you actually meant.
from decimal import Decimal
print(Decimal("0.1") + Decimal("0.2")) # exact
print(Decimal("0.1") + Decimal("0.2") == Decimal("0.3"))
print(Decimal("19.99") * 3) # three items
Decimal counts in tens like a human, so Decimal("0.1") +
Decimal("0.2") is exactly Decimal('0.3'), and comparing it with
Decimal("0.3") is True — the thing that failed for floats. The
last line, three items at 19.99, gives Decimal('59.97'), exact to
the cent. (Pass Decimal strings, not floats, or you'd hand it the
rounded value to begin with.)
print(2 ** 100) # integers: no size limit print(2.0 ** 53 == 2.0 ** 53 + 1) # floats: precision runs out
2 ** 100 prints 1267650600228229401496703205376 — every one of its
31 digits correct, because Python integers are exact and unbounded.
The float line prints True: above 2 ** 53 the representable numbers
have gaps, so 2.0 ** 53 + 1 rounds back to 2.0 ** 53 and the two
compare equal. Same arithmetic, two very different guarantees.
Check the concept
One question at a time. Unsure? Revisit the lecture, then answer.
The challenge
Pass the quiz to unlock the challenge — your code will still be waiting here.