gpt4 book ai didi

python - 断言数组几乎等于零

转载 作者:行者123 更新时间:2023-12-04 09:14:07 25 4
gpt4 key购买 nike

我正在为我的模拟编写单元测试,并想检查特定参数的结果(一个 numpy 数组)是否为零。由于计算不准确,也接受较小的值 (1e-7)。断言此数组在所有位置都接近 0 的最佳方法是什么?

  • np.testing.assert_array_almost_equal(a, np.zeros(a.shape))assert_allclose失败,因为相对公差是 inf (如果你切换参数,则为 1)Docu
  • 我觉得 np.testing.assert_array_almost_equal_nulp(a, np.zeros(a.shape))不够精确,因为它将差异与间距进行比较,因此对于 nulps >= 1 始终如此否则为 false 但没有说明 a 的振幅Docu
  • 使用np.testing.assert_(np.all(np.absolute(a) < 1e-7))基于 this question不给出任何详细的输出,我被其他人习惯了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)

在这种情况下,rtol 值无关紧要,因为如果计算公差,它会乘以 0:

atol + rtol * abs(desired)

更新:用更简单的标量 0 替换了 np.zeros_like(a)。正如@hintze 所指出的,np 数组比较也适用于标量。

关于python - 断言数组几乎等于零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63291594/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com