numpy.testing.assert_equal#

testing.assert_equal(actual, desired, err_msg='', verbose=True, *, strict=False)[源代码]#

如果两个对象不相等,则引发 AssertionError。

给定两个对象(标量、列表、元组、字典或 numpy 数组),检查这些对象的所有元素是否相等。在第一个冲突值处会引发异常。

此函数处理 NaN 比较,就好像 NaN 是一个“普通”数字一样。也就是说,如果两个对象在相同位置都有 NaN,则不会引发 AssertionError。这与 IEEE 关于 NaN 的标准相反,该标准规定 NaN 与任何值进行比较都必须返回 False。

参数:
actualarray_like

要检查的对象。

desiredarray_like

期望的对象。

err_msgstr, optional

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

verbosebool, optional

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

strictbool, optional

如果为 True,并且 actualdesired 参数中有一个是数组,则当参数的形状或数据类型不匹配时,将引发 AssertionError。如果两个参数都不是数组,则此参数无效。

版本 2.0.0 中新增。

引发:
AssertionError

如果 actual 和 desired 不相等。

备注

actualdesired 中一个是标量而另一个是 array_like 时,该函数会检查 array_like 的每个元素是否等于标量。请注意,因此空数组被视为等于标量。通过将 strict==True 设置为 True 可以禁用此行为。

示例

>>> np.testing.assert_equal([4, 5], [4, 6])
Traceback (most recent call last):
    ...
AssertionError:
Items are not equal:
item=1
 ACTUAL: 5
 DESIRED: 6

以下比较不会引发异常。输入中有 NaN,但它们在相同位置。

>>> np.testing.assert_equal(np.array([1.0, 2.0, np.nan]), [1, 2, np.nan])

如 Notes 部分所述,assert_equal 在一个参数是数组时对标量有特殊处理。在此,测试检查 x 中的每个值是否为 3。

>>> x = np.full((2, 5), fill_value=3)
>>> np.testing.assert_equal(x, 3)

使用 strict 在比较标量与不同形状的数组时引发 AssertionError。

>>> np.testing.assert_equal(x, 3, strict=True)
Traceback (most recent call last):
    ...
AssertionError:
Arrays are not equal

(shapes (2, 5), () mismatch)
 ACTUAL: array([[3, 3, 3, 3, 3],
       [3, 3, 3, 3, 3]])
 DESIRED: array(3)

strict 参数还确保数组数据类型匹配。

>>> x = np.array([2, 2, 2])
>>> y = np.array([2., 2., 2.], dtype=np.float32)
>>> np.testing.assert_equal(x, y, strict=True)
Traceback (most recent call last):
    ...
AssertionError:
Arrays are not equal

(dtypes int64, float32 mismatch)
 ACTUAL: array([2, 2, 2])
 DESIRED: array([2., 2., 2.], dtype=float32)