比较浮点数和Python中几乎相等的最佳方法是什么?

本文翻译自:What is the best way to compare floats for almost-equality in Python?

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/ 例如: https//randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/

What is the recommended way to deal with this in Python? 在Python中处理此问题的推荐方法是什么?

Surely there is a standard library function for this somewhere? 当然在某个地方有一个标准的库函数吗?


#1楼

参考:https://stackoom.com/question/ntCN/比较浮点数和Python中几乎相等的最佳方法是什么


#2楼

I would agree that Gareth's answer is probably most appropriate as a lightweight function/solution. 我同意Gareth的答案可能最适合作为轻量级功能/解决方案。

But I thought it would be helpful to note that if you are using NumPy or are considering it, there is a packaged function for this. 但是我认为最好注意一下,如果您正在使用NumPy或正在考虑使用它,则可以使用打包功能。

numpy.isclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False)

A little disclaimer though: installing NumPy can be a non-trivial experience depending on your platform. 不过有一点免责声明:根据您的平台,安装NumPy可能是不平凡的体验。


#3楼

我发现以下比较有帮助:

str(f1) == str(f2)

#4楼

For some of the cases where you can affect the source number representation, you can represent them as fractions instead of floats, using integer numerator and denominator. 对于某些可能影响源编号表示的情况,可以使用整数分子和分母将它们表示为小数而不是浮点数。 That way you can have exact comparisons. 这样,您可以进行精确比较。

See Fraction from fractions module for details. 有关详细信息,请参见“ 分数的分数”模块。


#5楼

Python 3.5 adds the math.isclose and cmath.isclose functions as described in PEP 485 . Python 3.5按照PEP 485中的描述添加了math.isclosecmath.isclose函数

If you're using an earlier version of Python, the equivalent function is given in the documentation . 如果您使用的是Python的早期版本,则等效功能在文档中给出。

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; rel_tol是一个相对公差,乘以两个自变量中的较大者; 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. abs_tol是在所有情况下abs_tol应用的绝对公差。 If the difference is less than either of those tolerances, the values are considered equal. 如果差异小于这些公差中的任何一个,则认为值相等。


#6楼

If you want to use it in testing/TDD context, I'd say this is a standard way: 如果要在测试/ TDD上下文中使用它,我会说这是一种标准方式:

from nose.tools import assert_almost_equals

assert_almost_equals(x, y, places=7) #default is 7
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值