在 Python 中比较浮点数是否相等的最佳方法是什么? [英] What is the best way to compare floats for almost-equality in Python?

查看:26
本文介绍了在 Python 中比较浮点数是否相等的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于在 Python 中比较浮点数是否相等的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆