[英]Assert array almost equal zero
I'm writing unit tests for my simulation and want to check that for specific parameters the result, a numpy array, is zero.我正在为我的模拟编写单元测试,并想检查特定参数的结果,numpy 数组是否为零。 Due to calculation inaccuracies, small values are also accepted (1e-7).由于计算不准确,也接受较小的值 (1e-7)。 What is the best way to assert this array is close to 0 in all places?断言这个数组在所有地方都接近 0 的最佳方法是什么?
np.testing.assert_array_almost_equal(a, np.zeros(a.shape))
and assert_allclose
fail as the relative tolerance is inf
(or 1 if you switch the arguments) Docu np.testing.assert_array_almost_equal(a, np.zeros(a.shape))
和assert_allclose
失败,因为相对容差为inf
(如果切换参数,则为 1) Docunp.testing.assert_array_almost_equal_nulp(a, np.zeros(a.shape))
is not precise enough as it compares the difference to the spacing, therefore it's always true for nulps >= 1
and false otherways but does not say anything about the amplitude of a
Docu我觉得np.testing.assert_array_almost_equal_nulp(a, np.zeros(a.shape))
不够精确,因为它将差异与间距进行了比较,因此对于nulps >= 1
和 false 其他情况总是如此,但什么也没说关于Docu a
幅度np.testing.assert_(np.all(np.absolute(a) < 1e-7))
based on this question does not give any of the detailed output, I am used to by other np.testing
methods基于这个问题使用np.testing.assert_(np.all(np.absolute(a) < 1e-7))
没有给出任何详细的 output,我习惯于其他np.testing
方法Is there another way to test this?有没有另一种方法来测试这个? Maybe another testing package?也许另一个测试 package?
If you compare a numpy array with all zeros, you can use the absolute tolerance, as the relative tolerance does not make sense here:如果将 numpy 数组与全零进行比较,则可以使用绝对容差,因为相对容差在这里没有意义:
from numpy.testing import assert_allclose
def test_zero_array():
a = np.array([0, 1e-07, 1e-08])
assert_allclose(a, np.zeros_like(a), atol=1e-07)
The rtol
value does not matter in this case, as it is multiplied with 0 if calculating the tolerance:在这种情况下, rtol
值无关紧要,因为如果计算公差,它会乘以 0:
atol + rtol * abs(desired)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.