Skip to Content
Course content

15: Floating-Point Numbers and Precision Issues

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I remember the first time I hit this bug. I was writing a simple script to track a budget, and I had a conditional check to see if the remaining balance was exactly zero. I knew the math added up, but the code just wouldn't enter the if block. I spent an hour questioning my sanity before I realized that Python—and almost every other programming language—is lying to you about how it stores decimals.

The Lie That 0.1 + 0.2 Equals 0.3

Most learners assume that if they type 0.1 into a script, Python stores exactly one-tenth. It feels intuitive. But try running this in your REPL right now:

print(0.1 + 0.2 == 0.3)
# Output: False

Wait, what? If you print the result of 0.1 + 0.2, you'll see 0.30000000000000004. That tiny sliver of a difference is enough to break your logic and crash your program's flow. This isn't a Python bug; it's a fundamental limitation of how computers handle numbers.

Binary Can't Always Count by Tenths

Here is the deal: humans use Base-10. In Base-10, we can easily represent 1/10 as 0.1. But computers use Base-2 (binary). In binary, some fractions that are clean in decimal become "repeating decimals" that go on forever.

Think about how 1/3 looks in our decimal system: 0.333333... No matter how many threes you write, you'll never actually reach exactly one-third. Binary has the same problem with 0.1. The computer has to cut that number off at some point to fit it into a 64-bit piece of memory (the IEEE 754 standard). When you add two of these "slightly off" numbers together, the errors compound, and you end up with that weird ...00004 at the end.

Stop Using == for Floats

Since you can't trust floats to be exact, you should almost never use the == operator with them. I've seen production systems fail because someone checked if a calculated coordinate was == 10.0. Instead, you should check if the two numbers are "close enough."

Python provides a built-in way to handle this in the math module called isclose(). It checks if the difference between two numbers is within a very small tolerance:

import math

a = 0.1 + 0.2
b = 0.3

if math.isclose(a, b):
    print("Close enough for government work!")

Now, if you're working on something where precision is non-negotiable—like a banking app or a medical dosage calculator—don't use floats at all. Use the decimal module. It's slower, but it stores numbers more like humans do, avoiding the binary conversion mess entirely.

from decimal import Decimal

# Note: Pass the numbers as strings to maintain precision
result = Decimal('0.1') + Decimal('0.2')
print(result == Decimal('0.3')) 
# Output: True

My rule of thumb: Use float for physics, graphics, or general data science. Use Decimal for money. And always use math.isclose() for comparisons.




📋 Practical Task

The Broken ATM Balance Fix

You've been handed a snippet of code for an ATM's "Zero Balance" notification system. The current code is failing to trigger the notification even when the user's account is effectively empty because of floating-point precision errors.

Your Task: Rewrite the check_balance function. You must ensure that the notification triggers if the balance is "effectively" zero, even if there is a tiny floating-point residue. You can choose either the math.isclose() approach or the Decimal approach.

import math

def check_balance(current_balance):
    # This is the broken line
    if current_balance == 0.0:
        return "Account is empty. Please deposit funds."
    return "Balance is sufficient."

# Test case: These deposits and withdrawals should result in 0.0
# But in float-land, they don't.
balance = 0.0
balance += 0.1
balance += 0.1
balance += 0.1
balance -= 0.3

print(f"Current Balance: {balance}")
print(check_balance(balance)) 
# Expected: "Account is empty. Please deposit funds."
# Actual result currently: "Balance is sufficient."
Rating
0 0

There are no comments for now.

to be the first to leave a comment.