numpy.testing.assert_allclose#
- testing.assert_allclose(actual, desired, rtol=1e-07, atol=0, equal_nan=True, err_msg='', verbose=True, *, strict=False)[原始碼]#
如果兩個物件在期望的容忍度內不相等,則引發 AssertionError。
給定兩個 array_like 物件,檢查它們的形狀和所有元素是否相等(但請參閱「Notes」以了解純量值的特殊處理方式)。如果形狀不符或任何值衝突,則會引發例外。與 numpy 中的標準用法相反,NaNs 會像數字一樣進行比較,如果兩個物件在相同位置都有 NaNs,則不會引發 assertion。
此測試等效於
allclose(actual, desired, rtol, atol)
(請注意,allclose
具有不同的預設值)。它將 actual 和 desired 之間的差異與atol + rtol * abs(desired)
進行比較。- 參數:
- actualarray_like
取得的陣列。
- desiredarray_like
期望的陣列。
- rtolfloat, optional
相對容忍度。
- atolfloat, optional
絕對容忍度。
- equal_nanbool, optional.
如果為 True,NaNs 將視為相等。
- err_msgstr, optional
在失敗時列印的錯誤訊息。
- verbosebool, optional
如果為 True,衝突的值將附加到錯誤訊息中。
- strictbool, optional
如果為 True,當引數的形狀或資料類型不符時,引發
AssertionError
。Notes 章節中提到的純量值的特殊處理方式將被停用。2.0.0 版本新增。
- 引發:
- AssertionError
如果 actual 和 desired 在指定的精確度內不相等。
Notes
當 actual 和 desired 其中之一是純量,而另一個是 array_like 時,此函數會執行比較,就好像純量值被廣播到陣列的形狀一樣。可以使用 strict 參數停用此行為。
範例
>>> x = [1e-5, 1e-3, 1e-1] >>> y = np.arccos(np.cos(x)) >>> np.testing.assert_allclose(x, y, rtol=1e-5, atol=0)
如 Notes 章節中所述,
assert_allclose
對於純量值有特殊的處理方式。在此,測試檢查numpy.sin
的值在 π 的整數倍數時是否接近於零。>>> x = np.arange(3) * np.pi >>> np.testing.assert_allclose(np.sin(x), 0, atol=1e-15)
使用 strict 在將一個或多個維度的陣列與純量值進行比較時,引發
AssertionError
。>>> np.testing.assert_allclose(np.sin(x), 0, atol=1e-15, strict=True) Traceback (most recent call last): ... AssertionError: Not equal to tolerance rtol=1e-07, atol=1e-15 (shapes (3,), () mismatch) ACTUAL: array([ 0.000000e+00, 1.224647e-16, -2.449294e-16]) DESIRED: array(0)
strict 參數也確保陣列資料類型相符
>>> y = np.zeros(3, dtype=np.float32) >>> np.testing.assert_allclose(np.sin(x), y, atol=1e-15, strict=True) Traceback (most recent call last): ... AssertionError: Not equal to tolerance rtol=1e-07, atol=1e-15 (dtypes float64, float32 mismatch) ACTUAL: array([ 0.000000e+00, 1.224647e-16, -2.449294e-16]) DESIRED: array([0., 0., 0.], dtype=float32)