You may know the following surprising code snippet:
a = 0.1 + 0.1 + 0.1 b = 0.3 print(a == b) # False
The following explanation is from the puzzle-based learning Python workbook:
This puzzle performs a simple arithmetic computation adding together the float value 0.1.
The question seems to be very simple—but as we’ll see in a moment, it’s not simple at all.
Your inner voice is wrong. And while it is not so important why it’s wrong, it is important that you learn to distrust your intuition and your urge to be a lazy thinker. In coding, assuming that things are super-simple is a deadly sin.
In the puzzle, you have assumed that the number 0.1 represents the decimal value 0.1 or 1/10. This is natural but a wrong assumption. The value 0.1 doesn’t exist on your computer. Instead, your computer stores every number in a binary format consisting only of zeros and ones.
Use an online converter to convert the decimal value 0.1 to a binary value and you will realize that you get the following number: 0.000110011001100110011…
The floating point representation of 0.1 in binary has an infinite number of digits. So your computer does the only thing it can do at this moment: limiting the number of digits.
This has the following effect. The decimal number of 0.1 is represented by the closest floating point number 0.100000000000000005551115… that can be represented in a limited space.
Now, it’s easy to see why
0.1 + 0.1 + 0.1 != 0.3. Thus the answer is
from decimal import Decimal a = 0.1 + 0.1 + 0.1 b = 0.3 print(a == b) # False c = Decimal('0.1') + Decimal('0.1') + Decimal('0.1') d = Decimal('0.3') print(c == d) # True
You can see that the equality of variables
d results in the expected value
Where to go from here?
Understanding these subtleties is hard. However, it’s also crucial on your path to killer Python efficiency.
A simple fix is to work through the “Coffee Break Python Workbook” until you have developed Python code-reading super-powers!
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.