numpy.testing.assert_allclose#
- testing.assert_allclose(actual, desired, rtol=1e-07, atol=0, equal_nan=True, err_msg='', verbose=True, *, strict=False)[源码]#
如果两个对象在期望的容差范围内不相等,则引发 AssertionError。
给定两个 array_like 对象,检查它们的形状和所有元素是否相等(但请参阅“备注”中对标量的特殊处理)。如果形状不匹配或任何值冲突,则会引发异常。与 NumPy 中的标准用法不同,NaNs(非数字)在此处被当作数字进行比较,如果两个对象在相同位置都有 NaNs,则不会引发断言。
此测试等同于
allclose(actual, desired, rtol, atol)
(请注意allclose
具有不同的默认值)。它将 actual 和 desired 之间的差异与atol + rtol * abs(desired)
进行比较。- 参数:
- actualarray_like
获得的数组。
- desiredarray_like
期望的数组。
- rtolfloat, 可选
相对容差。
- atolfloat, 可选
绝对容差。
- equal_nan布尔值, 可选。
如果为 True,NaNs 将被视为相等。
- err_msg字符串, 可选
失败时要打印的错误消息。
- verbose布尔值, 可选
如果为 True,冲突的值将附加到错误消息中。
- strict布尔值, 可选
如果为 True,当参数的形状或数据类型不匹配时,将引发
AssertionError
。在“备注”部分提到的对标量的特殊处理将被禁用。2.0.0 版本新增。
- 引发:
- AssertionError
如果 actual 和 desired 在指定精度范围内不相等。
备注
当 actual 和 desired 中的一个为标量而另一个为 array_like 时,该函数会像标量被广播到数组的形状一样执行比较。此行为可以通过 strict 参数禁用。
示例
>>> x = [1e-5, 1e-3, 1e-1] >>> y = np.arccos(np.cos(x)) >>> np.testing.assert_allclose(x, y, rtol=1e-5, atol=0)
如“备注”部分所述,
assert_allclose
对标量有特殊处理。在此,测试检查numpy.sin
在 π 的整数倍处的值接近零。>>> x = np.arange(3) * np.pi >>> np.testing.assert_allclose(np.sin(x), 0, atol=1e-15)
使用 strict 参数可在将具有一个或多个维度的数组与标量进行比较时引发
AssertionError
。>>> np.testing.assert_allclose(np.sin(x), 0, atol=1e-15, strict=True) Traceback (most recent call last): ... AssertionError: Not equal to tolerance rtol=1e-07, atol=1e-15 (shapes (3,), () mismatch) ACTUAL: array([ 0.000000e+00, 1.224647e-16, -2.449294e-16]) DESIRED: array(0)
strict 参数还确保数组数据类型匹配
>>> y = np.zeros(3, dtype=np.float32) >>> np.testing.assert_allclose(np.sin(x), y, atol=1e-15, strict=True) Traceback (most recent call last): ... AssertionError: Not equal to tolerance rtol=1e-07, atol=1e-15 (dtypes float64, float32 mismatch) ACTUAL: array([ 0.000000e+00, 1.224647e-16, -2.449294e-16]) DESIRED: array([0., 0., 0.], dtype=float32)