Comparing Floating-Point Numbers with Precision in Python
In the realm of programming, comparing floating-point numbers for equality presents challenges. As highlighted by experts like Bruce Dawson, determining equality is complicated by rounding errors and precision limitations.
Is there a Solution in Python?
Python offers a myriad of solutions to this issue. Notably, Python 3.5 introduces the math.isclose and cmath.isclose functions, following the guidance of PEP 485. These functions provide a reliable means of comparing floating-point numbers for approximate equality.
Implementation Details:
import math # Compare two floating-point numbers for almost-equality result = math.isclose(0.1, 0.10000000000000001, rel_tol=1e-09, abs_tol=0.0)
Custom Function for Earlier Python Versions:
For Python versions prior to 3.5, the documentation suggests the following custom function:
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)
Parameters Explained:
Using either the math.isclose function or the custom function ensures accurate comparison of floating-point numbers for approximate equality, addressing the challenges posed by precision issues.
The above is the detailed content of How Can I Accurately Compare Floating-Point Numbers in Python?. For more information, please follow other related articles on the PHP Chinese website!