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

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

Patricia Arquette
Release: 2024-12-18 11:49:10
Original
433 people have browsed it

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

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:

  • a and b: The floats to be compared
  • rel_tol (optional): A relative tolerance threshold
  • abs_tol (optional): An absolute tolerance threshold

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template