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

How to Compare Floating-Point Numbers for Near-Equality in Python?

Linda Hamilton
Linda HamiltonOriginal
2024-12-19 06:55:09752browse

How to Compare Floating-Point Numbers for Near-Equality in Python?

Floating-Point Comparison with Almost-Equality in Python

Comparing floating-point numbers for equality in Python can present challenges due to precision issues and rounding errors. To address this, it's essential to employ techniques that allow for a meaningful comparison.

One approach is to use the standard library function introduced in Python 3.5:

import math
math.isclose(a, b, rel_tol=1e-09, abs_tol=0.0)

The rel_tol parameter specifies a relative tolerance, which is a multiplier applied to the larger of the two numbers being compared. abs_tol represents an absolute tolerance applied directly to the difference between the numbers.

If the difference between a and b is less than either the relative or absolute tolerance, the two numbers are considered almost-equal and the function returns True. Otherwise, it returns False.

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)

The above is the detailed content of How to Compare Floating-Point Numbers for Near-Equality in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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