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

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

Susan Sarandon
Release: 2024-12-26 19:39:18
Original
571 people have browsed it

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

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

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

Parameters Explained:

  • rel_tol: Defines the relative tolerance, adjusting the acceptable difference based on the magnitude of the values being compared.
  • abs_tol: Specifies an absolute tolerance, allowing for direct comparison without considering the magnitude of the numbers.

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!

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