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, 可选

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

strictbool, 可选

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

在 2.0.0 版本加入.

提出:
AssertionError

如果 actual 和 desired 不相等.

注释

默认情况下,当 actualdesired 之一是标量,另一个是数组时,该函数检查数组的每个元素是否等于标量.可以通过设置 strict==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)