numpy.testing.assert_array_less#
- testing.assert_array_less(x, y, err_msg='', verbose=True, *, strict=False)[原始碼]#
如果兩個 array_like 物件並非以小於排序,則引發 AssertionError。
給定兩個 array_like 物件 x 和 y,檢查形狀是否相等,且 x 的所有元素是否嚴格小於 y 的對應元素(但請參閱「註解」中關於純量特殊處理的部分)。如果形狀不符或值未正確排序,則會引發例外。與 NumPy 中的標準用法相反,如果兩個物件在相同位置都具有 NaN,則不會引發 assertion。
- 參數:
- xarray_like
要檢查的較小物件。
- yarray_like
要比較的較大物件。
- err_msg字串
在失敗時要印出的錯誤訊息。
- verbose布林值
如果為 True,則衝突的值會附加到錯誤訊息中。
- strict布林值,選用
如果為 True,當 array_like 物件的形狀或資料類型不符時,引發 AssertionError。「註解」章節中提及的純量特殊處理將會停用。
2.0.0 版本新增。
- 引發:
- AssertionError
如果 x 並非逐元素嚴格小於 y。
另請參閱
assert_array_equal
測試物件是否相等
assert_array_almost_equal
測試物件是否在精度範圍內相等
註解
當 x 和 y 其中之一是純量,而另一個是 array_like 時,此函數會執行比較,如同純量已廣播到陣列的形狀。可以使用 strict 參數停用此行為。
範例
以下 assertion 通過,因為 x 的每個有限元素都嚴格小於 y 的對應元素,且 NaN 位於對應的位置。
>>> x = [1.0, 1.0, np.nan] >>> y = [1.1, 2.0, np.nan] >>> np.testing.assert_array_less(x, y)
以下 assertion 失敗,因為 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%) 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 比較,且 assertion 通過。
>>> x = [1.0, 4.0] >>> y = 5.0 >>> np.testing.assert_array_less(x, y)
但是,使用
strict=True
,assertion 將會失敗,因為形狀不符。>>> 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 不符,assertion 也會失敗。>>> 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])