Home >Backend Development >Python Tutorial >How Can I Accurately Compare Floating-Point Numbers for Near-Equality in Python?
Comparing Floats for Almost-Equality in Python: A Closer Look
Due to potential rounding and precision issues, comparing floats for exact equality in Python can be challenging. This is a well-known issue, as highlighted in Bruce Dawson's "Comparing Floating Point Numbers, 2012 Edition" blog post. To address this challenge effectively in Python, several approaches can be considered.
Standard Library Functions
Python 3.5 introduced the math.isclose() and cmath.isclose() functions, which are specifically designed for comparing floats with a tolerance level. These functions accept three arguments:
If the absolute difference between a and b is less than either rel_tol * max(abs(a), abs(b)) or abs_tol, the values are considered equal.
Custom Function for Earlier Python Versions
If you are using a Python version earlier than 3.5, you can implement your own isclose() function based on the following code snippet provided in the documentation:
def isclose(a, b, rel_tol=1e-09, abs_tol=0.0): return abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
This custom function offers the same functionality as the standard library function, allowing you to compare floats within a specified tolerance range.
The above is the detailed content of How Can I Accurately Compare Floating-Point Numbers for Near-Equality in Python?. For more information, please follow other related articles on the PHP Chinese website!