Decimal: Python’s Float Trap and How to Solve it

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:

Get eBook!

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 False.

As one of my premium members, Albrecht, correctly pointed out, the problem can be fixed with the Python module Decimal:

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 c and d results in the expected value True.

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!

Leave a Comment

Your email address will not be published. Required fields are marked *