Home > Backend Development > Python Tutorial > How Can I Accurately Compare Floating-Point Numbers for Near-Equality in Python?

How Can I Accurately Compare Floating-Point Numbers for Near-Equality in Python?

DDD
Release: 2024-12-22 19:24:11
Original
668 people have browsed it

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:

  • a and b: The float values to be compared
  • rel_tol (optional): The relative tolerance, which is a factor applied to the larger magnitude of a and b to define the allowed difference
  • abs_tol (optional): An absolute tolerance, which sets a minimum difference threshold

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)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template