使用值接近 0 的 math.isclose 函数
Using math.isclose function with values close to 0
正如我们所知,由于数字的二进制表示,此表达式的计算结果为 False
(至少在 Python 中):
0.2 + 0.4 == 0.6
为了能够检查数值错误中的相等性,模块 math
提供 isclose
:
import math
math.isclose(0.2 + 0.4 , 0.6)
最后一个表达式按预期产生 True
。
现在为什么下面的表达式又是False
?
math.isclose(0.2 + 0.4 - 0.6 , 0.0)
似乎与 0.0
相比的一切都是 False
math.isclose(1.0e-100 , 0.0)
阅读documentation即可得出答案。
math.isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)
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 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 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)
您使用默认容差,这意味着使用了相对容差检查。上面的等式清楚地说明了为什么您的表达式计算为假。
考虑问题中的最后一个表达式:
math.isclose(1.0e-100 , 0.0)
将这些值代入文档中的表达式,我们得到
1.0e-100 <= max(1.0e-9 * 1.0e-100, 0.0)
我认为很明显,在执行相对公差比较时,使用默认公差,没有非零值被视为接近零。
对于非常小的值,您或许应该使用绝对公差。
或者您应该重新编写测试以避免与零进行比较。
正如我们所知,由于数字的二进制表示,此表达式的计算结果为 False
(至少在 Python 中):
0.2 + 0.4 == 0.6
为了能够检查数值错误中的相等性,模块 math
提供 isclose
:
import math
math.isclose(0.2 + 0.4 , 0.6)
最后一个表达式按预期产生 True
。
现在为什么下面的表达式又是False
?
math.isclose(0.2 + 0.4 - 0.6 , 0.0)
似乎与 0.0
相比的一切都是 False
math.isclose(1.0e-100 , 0.0)
阅读documentation即可得出答案。
math.isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)
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 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 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)
您使用默认容差,这意味着使用了相对容差检查。上面的等式清楚地说明了为什么您的表达式计算为假。
考虑问题中的最后一个表达式:
math.isclose(1.0e-100 , 0.0)
将这些值代入文档中的表达式,我们得到
1.0e-100 <= max(1.0e-9 * 1.0e-100, 0.0)
我认为很明显,在执行相对公差比较时,使用默认公差,没有非零值被视为接近零。
对于非常小的值,您或许应该使用绝对公差。
或者您应该重新编写测试以避免与零进行比较。