Caa*_*rch 5 python arrays unit-testing assert
我正在为我的模拟编写单元测试,并希望检查特定参数的结果(numpy 数组)是否为零。由于计算不准确,也可以接受较小的值 (1e-7)。断言该数组在所有位置都接近 0 的最佳方法是什么?
np.testing.assert_array_almost_equal(a, np.zeros(a.shape))并失败,assert_allclose因为相对容差为inf(如果切换参数则为 1)np.testing.assert_array_almost_equal_nulp(a, np.zeros(a.shape))不够精确,因为它比较了间距的差异,因此它总是 true for和 false otherways 但没有说明Docunulps >= 1的幅度a np.testing.assert_(np.all(np.absolute(a) < 1e-7))基于这个问题的使用不会给出任何详细的输出,我习惯于通过其他np.testing方法还有其他方法可以测试这个吗?也许另一个测试包?
如果将 numpy 数组与全零进行比较,则可以使用绝对容差,因为相对容差在这里没有意义:
from numpy.testing import assert_allclose
def test_zero_array():
a = np.array([0, 1e-07, 1e-08])
assert_allclose(a, 0, atol=1e-07)
Run Code Online (Sandbox Code Playgroud)
在这种情况下,该rtol值并不重要,因为如果计算容差,则该值会乘以 0:
atol + rtol * abs(desired)
Run Code Online (Sandbox Code Playgroud)
更新:替换np.zeros_like(a)为更简单的标量 0。正如@hintze 所指出的,np 数组比较也适用于标量。