问题描述
我们知道,由于数字的二进制表示,该表达式的计算结果为False
(至少在Python中):
As we know, due to the binary representation of numbers, this expression evaluates to False
(at least in Python):
0.2 + 0.4 == 0.6
为了能够在数值误差内检查相等性,模块math
提供了isclose
:
In order to be able to check for equality within numerical errors, the module math
offers isclose
:
import math
math.isclose(0.2 + 0.4 , 0.6)
最后一个表达式产生预期的True
.
This last expression yields True
as expected.
现在为什么下面的表达式又是False
?
Now why does this following expression is False
again?
math.isclose(0.2 + 0.4 - 0.6 , 0.0)
与0.0
相比,一切似乎都是False
It appears that everything compared to 0.0
is False
math.isclose(1.0e-100 , 0.0)
推荐答案
可以通过阅读.
math.isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)
如果值a和b彼此接近,则返回True,否则返回False.
Return True if the values a and b are close to each other and False otherwise.
根据给定的绝对和相对公差确定是否认为两个值接近.
Whether or not two values are considered close is determined according to given absolute and relative tolerances.
rel_tol是相对公差–它是a和b之间的最大允许差,相对于a或b的较大绝对值.例如,要将公差设置为5%,请通过rel_tol = 0.05.默认容差为1e-09,可确保两个值在大约9个十进制数字内相同. rel_tol必须大于零.
rel_tol is the relative tolerance – it is the maximum allowed difference between a and b, relative to the larger absolute value of a or b. For example, to set a tolerance of 5%, pass rel_tol=0.05. The default tolerance is 1e-09, which assures that the two values are the same within about 9 decimal digits. rel_tol must be greater than zero.
abs_tol是最小绝对公差–对接近零的比较很有用. abs_tol必须至少为零.
abs_tol is the minimum absolute tolerance – useful for comparisons near zero. abs_tol must be at least zero.
如果没有错误发生,结果将是:
If no errors occur, the result will be:
abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
您使用默认公差,这意味着将使用相对公差检查.上面的等式清楚表明了您的表达式为何计算为假.
You use default tolerances which means that a relative tolerance check is used. And the equation above makes it clear why your expressions evaluates false.
考虑问题中的最终表达式:
Consider the final expression in the question:
math.isclose(1.0e-100 , 0.0)
将这些值插入文档中的表达式中,我们就有
Plug these values into the expression from the documentation and we have
1.0e-100 <= max(1.0e-9 * 1.0e-100, 0.0)
我认为显而易见的是,在使用默认公差执行相对公差比较时,不会将任何非零值都视为接近零.
I think it should be obvious that when performing a relative tolerance comparison, using default tolerances, no non-zero value is deemed close to zero.
对于非常小的值,您也许应该使用绝对公差.
For very small values you should perhaps use an absolute tolerance.
或者您应该重新编写测试以避免与零进行比较.
Or you should re-write the test to avoid comparing against zero.
这篇关于使用math.isclose函数的值接近0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!