Python Float Comparison Precision Fix
In this tutorial, you'll learn about Python Float Comparison Precision Fix. We cover key concepts, practical examples, and best practices.
Floating-point arithmetic in Python produces results like 0.1 + 0.2 == 0.3 returning False. This is not a bug — it is inherent to how IEEE 754 floating-point numbers work. Direct equality comparison of floats is unreliable.
The Problem
a = 0.1 + 0.2
b = 0.3
print(f"a = {a}, b = {b}")
print(f"a == b: {a == b}")
Output:
a = 0.30000000000000004, b = 0.3
a == b: False
Wrong Code
# WRONG — direct float comparison
def calculate_tax(amount, rate=0.1):
return amount * rate
total = 100 * 0.1
if total == 10.0:
print("Tax calculated correctly")
Right Code
import math
a = 0.1 + 0.2
b = 0.3
# Use math.isclose for float comparison
if math.isclose(a, b, rel_tol=1e-9):
print(f"{a} is close to {b}")
Expected output:
0.30000000000000004 is close to 0.3
Step-by-Step Fix
Step 1: Understand the precision issue
# Display full precision
print(f"0.1 + 0.2 = {0.1 + 0.2:.20f}")
print(f"0.3 = {0.3:.20f}")
Step 2: Use math.isclose for comparison
import math
print(math.isclose(0.1 + 0.2, 0.3)) # True
print(math.isclose(0.1, 0.1000000001, rel_tol=1e-6)) # True
Step 3: Use Decimal for exact arithmetic
from decimal import Decimal
a = Decimal('0.1') + Decimal('0.2')
b = Decimal('0.3')
print(f"a == b: {a == b}") # True
# Decimal is exact but slower than float
Step 4: Compare with tolerance manually
def approx_equal(a, b, tolerance=1e-10):
return abs(a - b) < tolerance
print(approx_equal(0.1 + 0.2, 0.3)) # True
Step 5: Round before comparison
value = 0.1 + 0.2
rounded = round(value, 2)
print(rounded == 0.3) # True
Step 6: Use integer arithmetic where possible
# Instead of floats for currency
cents = 10 + 20 # represents 0.10 + 0.20
print(cents == 30) # True — exact integer comparison
Prevention Tips
- Never compare floats directly with
== - Use
math.isclose()with appropriate tolerances - Use
Decimalfor financial calculations - Use integers for currency (cents, pennies)
- Be aware that float precision limits to about 15-17 significant digits
Common Mistakes with float comparison
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro