問(wèn)題描述
眾所周知,由于舍入和精度問(wèn)題,比較浮點(diǎn)數(shù)是否相等有點(diǎn)繁瑣.
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 中處理此問(wèn)題的推薦方法是什么?
What is the recommended way to deal with this in Python?
在某個(gè)地方肯定有一個(gè)標(biāo)準(zhǔn)庫(kù)函數(shù)嗎?
Surely there is a standard library function for this somewhere?
推薦答案
Python 3.5 添加了 math.isclose
和 cmath.isclose
函數(shù),如 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
是一個(gè)相對(duì)容差,它乘以兩個(gè)參數(shù)中較大的一個(gè);隨著值變大,它們之間的允許差異也會(huì)變大,同時(shí)仍然認(rèn)為它們相等.
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
是在所有情況下按原樣應(yīng)用的絕對(duì)公差.如果差值小于這些公差中的任何一個(gè),則認(rèn)為這些值相等.
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.
這篇關(guān)于在 Python 中比較浮點(diǎn)數(shù)是否相等的最佳方法是什么?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!