Boss lesson · Unit 01
Why 0.1 + 0.2 isn't 0.3
How fractions are stored, and how to live with it
What you practise
- Binary fractions, sign/exponent/mantissa, rounding error, comparing with a tolerance, why money is stored in cents, where integers stop being exact (2⁵³)
Try a question from this lesson
Pick one
Trust your instinct, then check it against the explanation. What does this print?
print(0.1 + 0.2 == 0.3)Correct answer
False
Why
False, in Python, JavaScript, C and almost every other language. The machine is not broken: none of these three numbers can be stored exactly in binary. This lesson is about why.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Fractions in binary
After the point, binary places are worth 1/2, 1/4, 1/8... So 0.75 is 0.11 in binary: exact.
But 0.1 is like 1/3 in decimal: its binary digits (0.000110011...) repeat forever. A float has 64 bits, so it stores the nearest value it can reach.
print(0.5 + 0.25 == 0.75) # True
print(f"{0.1:.20f}")
# 0.10000000000000000555Concept
Inside a float
A float is scientific notation in binary. Its 64 bits are a sign, an exponent (how far to move the point) and 52 fraction bits.
With the leading 1 that gives 53 significant bits: about 16 decimal digits of precision, wherever the point sits.
sign exponent fraction
[ 1 ] [ 11 ] [ 52 ] bits
value = +/- 1.fraction x 2^exponent10 more exercises in the app
- 5× multiple choice
- 2× type the answer
- 1× fill the blanks
- 1× order the lines
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.