0
0
PythonHow-ToBeginner · 3 min read

How to Compare Float Numbers in Python: Simple and Accurate Methods

To compare float numbers in Python, use a tolerance-based approach with abs(a - b) < tolerance because direct equality with == can fail due to precision errors. Alternatively, use math.isclose() for a built-in, reliable comparison.
📐

Syntax

Comparing floats directly with == can be unreliable. Instead, use a tolerance value to check if two floats are close enough.

  • abs(a - b) < tolerance: Checks if the difference between a and b is smaller than a small number called tolerance.
  • math.isclose(a, b, rel_tol=..., abs_tol=...): Built-in function to compare floats with relative and absolute tolerance.
python
import math

# Using absolute tolerance
abs(a - b) < tolerance

# Using math.isclose
math.isclose(a, b, rel_tol=1e-9, abs_tol=0.0)
💻

Example

This example shows how to compare two float numbers using both a manual tolerance check and math.isclose(). It demonstrates why direct equality can fail.

python
import math

a = 0.1 + 0.2
b = 0.3

tolerance = 1e-9

# Direct comparison
print('Direct == comparison:', a == b)

# Using absolute tolerance
print('Tolerance check:', abs(a - b) < tolerance)

# Using math.isclose
print('math.isclose:', math.isclose(a, b, rel_tol=1e-9))
Output
Direct == comparison: False Tolerance check: True math.isclose: True
⚠️

Common Pitfalls

Directly comparing floats with == often fails because floats can have tiny rounding errors. For example, 0.1 + 0.2 is not exactly 0.3 in binary floating-point.

Always use a tolerance or math.isclose() to avoid unexpected results.

python
a = 0.1 + 0.2
b = 0.3

# Wrong way
print(a == b)  # False because of tiny precision error

# Right way
import math
print(math.isclose(a, b))  # True because it allows small differences
Output
False True
📊

Quick Reference

Use this quick guide when comparing floats:

MethodDescriptionExample
Direct == comparisonNot reliable due to precision errorsa == b # Avoid
Absolute tolerance checkCheck if difference is less than a small numberabs(a - b) < 1e-9
math.isclose()Built-in function with relative and absolute tolerancemath.isclose(a, b, rel_tol=1e-9)

Key Takeaways

Never compare floats directly with == due to precision errors.
Use a small tolerance value to check if floats are close enough.
Prefer math.isclose() for clear and reliable float comparisons.
Understand that floating-point arithmetic can introduce tiny errors.
Set tolerance values based on the precision needs of your program.