numpy.testing中的assert_allclose函数的相关测试和示例
numpy.testing.assert_allclose 函数是 NumPy 模块中的一个测试函数,用于检查两个数组或数值之间的相似性。该函数是 assert_allclose(用于检查数组)和 assert_almost_equal(用于标量比较)的组合版本。
assert_allclose 函数的使用语法如下:
numpy.testing.assert_allclose(actual, desired, rtol=1e-7, atol=0, equal_nan=True)
其中,
- actual:待测试的实际值(数组或数值)。
- desired:期望的结果(数组或数值)。
- rtol:相对容差(默认为 1e-7)。如果 rtol 为非负数,则 actual 和 desired 之间的绝对误差应小于 rtol * desired。
- atol:绝对容差(默认为 0)。如果 atol 为非负数,则 actual 和 desired 之间的绝对差应小于 atol。
- equal_nan:指定是否将 NaN 视为相等(默认为 True)。如果为 True,则两个 NaN 将被视为相等。
assert_allclose 函数会比较 actual 和 desired 之间的差异,并在差异超出容忍范围时引发 AssertionError 错误,从而表明测试未通过。
下面是一些使用 assert_allclose 函数的示例:
**示例1:数组比较**
import numpy as np # 定义两个数组 actual = np.array([0.1, 0.2, 0.3]) desired = np.array([0.11, 0.19, 0.3]) # 使用 assert_allclose 检查两个数组的相似性 np.testing.assert_allclose(actual, desired, rtol=0.1, atol=0.01)
在这个例子中,actual 数组和 desired 数组之间的差异是可接受的,因为相对容差 rtol=0.1 和绝对容差 atol=0.01 都是满足的。
**示例2:标量比较**
import numpy as np # 定义两个标量值 actual = 0.1 desired = 0.11 # 使用 assert_allclose 检查两个标量值的相似性 np.testing.assert_allclose(actual, desired, rtol=0.1, atol=0.01)
这个例子中使用了 actual 标量值和 desired 标量值进行比较,其中相对容差 rtol=0.1 和绝对容差 atol=0.01 都是满足的。
**示例3:指定 NaN 的相等性**
import numpy as np # 定义包含 NaN 的数组 actual = np.array([0.1, np.nan, 0.3]) desired = np.array([0.11, np.nan, 0.3]) # 使用 assert_allclose 检查两个数组的相似性,将 NaN 视为相等 np.testing.assert_allclose(actual, desired, rtol=0.1, atol=0.01, equal_nan=True)
在这个例子中,actual 数组和 desired 数组都包含 NaN 值。由于指定了 equal_nan=True,因此两个 NaN 值将被视为相等,所以该测试通过。
以上示例展示了如何使用 np.testing.assert_allclose 函数进行数组或数值的测试。你可以根据实际情况调整相对容差和绝对容差的值,以满足你的测试需求。
