Approximating Float Equality in Python: Standard Library Functions to the Rescue
It is widely recognized that comparing floats for exact equality can be problematic due to floating-point precision limitations, rendering simple equality checks unreliable. How can we overcome this challenge in Python?
Python's Built-in Solution
Python version 3.5 introduced two essential functions for this purpose: math.isclose and cmath.isclose. These functions, as defined in PEP 485, enable robust comparison of floats while accounting for precision-related discrepancies.
The isclose Function
The isclose function takes three parameters:
rel_tol represents a percentage of deviation allowed relative to the magnitudes of a and b. abs_tol, on the other hand, is an absolute threshold that must be met regardless of the magnitudes.
Tolerance Considerations
The function compares the absolute difference between a and b to both rel_tol * max(|a|, |b|) and abs_tol. If the difference is less than either of these values, the floats are considered equal.
Equivalent Implementation for Earlier Python Versions
For Python versions prior to 3.5, an equivalent function can be defined as follows:
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)
Utilizing this function allows you to confidently compare floats for approximate equality, an invaluable tool when working with numerical data in Python.
The above is the detailed content of How Can I Reliably Compare Floating-Point Numbers for Equality in Python?. For more information, please follow other related articles on the PHP Chinese website!