欢迎访问宙启技术站
智能推送

numpy.testingassert_allclose()函数的用途及参数解析

发布时间:2024-01-15 07:57:30

numpy.testing.assert_allclose()函数用于检查两个数组或对象是否在某个容许的误差范围内相等。

函数参数解析:

numpy.testing.assert_allclose(actual, desired, rtol=1e-07, atol=0, equal_nan=True, err_msg='', verbose=True)

参数解析:

1. actual: 被测数组或对象。

2. desired: 期望的数组或对象。

3. rtol: 相对容许误差的阈值,默认为1e-07。

4. atol: 绝对容许误差的阈值,默认为0。

5. equal_nan: 是否将 NaN 视为相等,默认为 True。

6. err_msg: 断言出错时显示的错误信息,默认为空。

7. verbose: 是否显示错误信息,默认为 True。

函数用例:

import numpy as np

from numpy.testing import assert_allclose

# 例子1: 相等性检查(默认容许误差)

x = np.array([1, 2, 3])

y = np.array([1.1, 2.2, 3.3])

assert_allclose(x, y)  # 无异常,通过检查

# 例子2: 自定义容许误差

x = np.array([1, 2, 3])

y = np.array([1.01, 2.02, 3.03])

assert_allclose(x, y, rtol=0.1, atol=0.02)  # 无异常,通过检查

# 例子3: 检查数组是否全是 NaN

x = np.full(5, np.nan)

y = np.array([np.nan] * 5)

assert_allclose(x, y)  # 无异常,通过检查

# 例子4: 异常情况(不通过检查)

x = np.array([1, 2, 3])

y = np.array([1.2, 2.3, 3.4])

assert_allclose(x, y)

# AssertionError: 

# Not equal to tolerance rtol=1e-07, atol=0

# 例子5: 自定义错误信息

x = np.array([1, 2, 3])

y = np.array([1.2, 2.3, 3.4])

assert_allclose(x, y, err_msg='Arrays are not close')

# AssertionError: Arrays are not close