Chapter 9
Computer Memory: Floats
Predict what this code will do when it runs:
x = 0
while x != 1:
x += 0.1
Then run it. Are you surprised? Ctrl-C, in case you have forgotten.
What is going on here? Isn’t 0.1 the same as 1/10?
The explanation is subtle, but it affects every floating-point computer program
in the world, including some used in life-or-death situations. The basic issue
is that, like integers, floating-p oint numbers are stored in binary rather than
decimal form.
Binary Fractions
In base ten, you are familiar with the fact that 1/3 has an infinitely-repeating
decimal form, 0.33333333 . . .. If we used base ten computers, you would prob-

Get A Concise Introduction to Programming in Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.