numpy.testing.assert_equal#

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

若兩個物件不相等,則引發 AssertionError。

給定兩個物件(純量、列表、元組、字典或 NumPy 陣列),檢查這些物件的所有元素是否相等。在第一個衝突值處會引發例外。

此函數處理 NaN 比較,如同 NaN 是「正常」數字一樣。也就是說,如果兩個物件在相同位置都有 NaN,則不會引發 AssertionError。這與 IEEE 關於 NaN 的標準相反,該標準指出 NaN 與任何東西比較都必須返回 False。

參數:
actualarray_like

要檢查的物件。

desiredarray_like

預期的物件。

err_msgstr, 選填

在失敗時要印出的錯誤訊息。

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

如「註解」章節中所述,當參數之一是陣列時,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)