在 Python 中比较浮点数是否相等的最佳方法是什么?

2022-01-09 00:00:00 python floating-point

问题描述

众所周知,由于舍入和精度问题,比较浮点数是否相等有点繁琐.

It's well known that comparing floats for equality is a little fiddly due to rounding and precision issues.

例如:https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/

在 Python 中处理此问题的推荐方法是什么?

What is the recommended way to deal with this in Python?

在某个地方肯定有一个标准库函数吗?

Surely there is a standard library function for this somewhere?


解决方案

Python 3.5 添加了 math.isclosecmath.isclose 函数,如 PEP 485.

Python 3.5 adds the math.isclose and cmath.isclose functions as described in PEP 485.

如果您使用的是早期版本的 Python,则在 文档.

If you're using an earlier version of Python, the equivalent function is given 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)

rel_tol 是一个相对容差,它乘以两个参数中较大的一个;随着值变大,它们之间的允许差异也会变大,同时仍然认为它们相等.

rel_tol is a relative tolerance, it is multiplied by the greater of the magnitudes of the two arguments; as the values get larger, so does the allowed difference between them while still considering them equal.

abs_tol 是在所有情况下按原样应用的绝对公差.如果差值小于这些公差中的任何一个,则认为这些值相等.

abs_tol is an absolute tolerance that is applied as-is in all cases. If the difference is less than either of those tolerances, the values are considered equal.

相关文章