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

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

问题描述



例如:
https://randomascii.wordpress.com/2012/02/25/比较浮点数-2012-edition /

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



当然在这个地方有一个标准的库函数吗?

解决方案

Python 3.5增加了 数学.isclose cmath.isclose 函数,如 PEP 485

如果你使用Python的早期版本,给出在 documentation



<$ p (ab,)<= c $ c> def isclose(a,b,rel_tol = 1e-09,abs_tol = 0.0):
return abs(ab)<= max(rel_tol * max(abs(a), abs(b)),abs_tol)

rel_tol 是相对容差,它乘以两个参数的大小中较大的一个;随着价值变大,他们之间允许的差异同样仍然考虑他们相等。

$ p $ abs_tol 是一个在所有情况下应用的绝对容忍度。如果差值小于这两个公差中的任何一个,则认为这些值相等。

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

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

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

Surely there is a standard library function for this somewhere?

解决方案

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

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 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 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天全站免登陆