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),但它更严格:它不广播其操作数,并且具有更严格的默认容差值。它将 actualdesired 之间的差值与 atol + rtol * abs(desired) 进行比较。

参数:
actualarray_like

获取的数组。

desiredarray_like

期望的数组。

rtolfloat, optional

相对容差。

atolfloat, optional

绝对容差。

equal_nanbool, optional.

如果为 True,则 NaNs 会被视为相等。

err_msgstr, optional

失败时要打印的错误消息。

verbosebool, optional

如果为 True,则将冲突的值附加到错误消息中。

strictbool, optional

如果为 True,则在参数的形状或数据类型不匹配时引发 AssertionError。说明部分中提到的标量特殊处理将被禁用。

版本 2.0.0 中新增。

引发:
AssertionError

如果 actual 和 desired 在指定精度内不相等。

备注

actualdesired 中有一个是标量而另一个是 array_like 时,该函数将执行比较,就好像标量被广播到数组的形状一样。请注意,因此空数组被视为与标量相等。通过将 strict==True 设置为 True,可以禁用此行为。

示例

>>> 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)