numpy.testing.assert_array_less#

testing.assert_array_less(x, y, err_msg='', verbose=True, *, strict=False)[source]#

如果两个 array_like 对象不满足小于关系,则引发 AssertionError。

给定两个 array_like 对象 xy,检查形状是否相等,并且 x 的所有元素是否严格小于 y 的相应元素(但请参阅 Notes 部分关于标量的特殊处理)。在形状不匹配或值未正确排序时会引发异常。与 NumPy 的标准用法相反,如果两个对象在相同位置都有 NaN,则不会引发断言。

参数:
xarray_like

较小的对象,用于检查。

yarray_like

较大的对象,用于比较。

err_msgstring

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

verbosebool

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

strictbool, optional

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

版本 2.0.0 中新增。

引发:
AssertionError

如果 x 不严格小于 y,逐元素进行。

另请参阅

assert_array_equal

测试对象的相等性

assert_array_almost_equal

以精度为准测试对象相等性

备注

xy 中的一个为标量,另一个为 array_like 时,该函数将进行比较,就好像标量已广播到数组的形状一样。此行为可以通过 strict 参数禁用。

示例

以下断言通过,因为 x 的每个有限元素都严格小于 y 的相应元素,并且 NaN 位于相应的位置。

>>> x = [1.0, 1.0, np.nan]
>>> y = [1.1, 2.0, np.nan]
>>> np.testing.assert_array_less(x, y)

以下断言失败,因为 x 的第零个元素不再严格小于 y 的第零个元素。

>>> y[0] = 1
>>> np.testing.assert_array_less(x, y)
Traceback (most recent call last):
    ...
AssertionError:
Arrays are not strictly ordered `x < y`

Mismatched elements: 1 / 3 (33.3%)
Mismatch at index:
 [0]: 1.0 (x), 1.0 (y)
Max absolute difference among violations: 0.
Max relative difference among violations: 0.
 x: array([ 1.,  1., nan])
 y: array([ 1.,  2., nan])

在此处,y 是一个标量,因此 x 的每个元素都与 y 进行比较,并且断言通过。

>>> x = [1.0, 4.0]
>>> y = 5.0
>>> np.testing.assert_array_less(x, y)

但是,当 strict=True 时,由于形状不匹配,断言将失败。

>>> np.testing.assert_array_less(x, y, strict=True)
Traceback (most recent call last):
    ...
AssertionError:
Arrays are not strictly ordered `x < y`

(shapes (2,), () mismatch)
 x: array([1., 4.])
 y: array(5.)

strict=True 时,如果两个数组的 dtype 不匹配,断言也会失败。

>>> y = [5, 5]
>>> np.testing.assert_array_less(x, y, strict=True)
Traceback (most recent call last):
    ...
AssertionError:
Arrays are not strictly ordered `x < y`

(dtypes float64, int64 mismatch)
 x: array([1., 4.])
 y: array([5, 5])