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

numpy.testingassert_allclose()函数的性能特点及使用技巧

发布时间:2024-01-15 08:00:04

numpy.testing.assert_allclose()函数用于测试两个数组或标量的近似相等性。他的性能特点是可以快速比较两个数组或标量的近似相等性,并抛出异常来指示测试结果。

使用技巧:

1. 在使用assert_allclose()函数时,可以通过设置参数来自定义测试的精度和容差。其中,参数rtol用于控制相对容差,默认值是1e-07;参数atol用于控制绝对容差,默认值是0;参数equal_nan用于控制是否将NaN视为相等,默认值是False;

import numpy as np
from numpy.testing import assert_allclose

a = np.array([1, 2, 3])
b = np.array([1.01, 2.02, 3.03])
assert_allclose(a, b, rtol=0.1)  # 设置相对容差为0.1

# Output: AssertionError: 
# 
# Not equal to tolerance rtol=0.1, atol=0
# 
# Mismatched elements: 3 / 3 (100%)
# Max absolute difference: 0.030000000000000027
# Max relative difference: 0.018666666666666665

2. 在比较多维数组时,可以通过设置参数axis来指定沿哪个轴进行比较,默认值是None,表示将数组展平后进行比较。

import numpy as np
from numpy.testing import assert_allclose

a = np.array([[1, 2, 3], [4, 5, 6]])
b = np.array([[1.01, 2.02, 3.03], [4.01, 5.02, 6.03]])
assert_allclose(a, b, rtol=0.1, axis=0)  # 沿第 0 轴进行比较

# Output: AssertionError:
# 
# Not equal to tolerance rtol=0.1, atol=0
# 
# Mismatched elements: 2 / 6 (33.3%)
# Max absolute difference: 0.030000000000000027
# Max relative difference: 0.018666666666666665

3. assert_allclose()函数还支持对标量进行比较。在比较标量时,可以通过设置参数err_msg来指定测试失败时的异常消息。

from numpy.testing import assert_allclose

a = 1.01
b = 1.02
assert_allclose(a, b, rtol=0.01, atol=0.01, err_msg='a is not close to b') 

# Output: AssertionError: 
# 
# a is not close to b
# 
# Not equal to tolerance rtol=0.01, atol=0.01
# 
# x: 1.01, y: 1.02, diff: 0.010000000000000009
#