問題描述
眾所周知,由于舍入和精度問題,比較浮點數是否相等有點繁瑣.
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.isclose
和 cmath.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 中比較浮點數是否相等的最佳方法是什么?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!