numpy.testing.assert_array_almost_equal

本文详细解释了如何使用numpy的assert_array_almost_equal函数检查两个数组是否在指定精度下相等,以及其设置规则。通过示例展示了当输入数组a和b存在微小误差时,如何引发AssertionError。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

assert_array_almost_equal(x,y,decimal=6,err_msg=' ',verbose=True)

如果x,y不满足一定精度的误差的话,会报错,decimal默认为6。

精度的设置是:abs(desired-actual) < 1.5 * 10**(-decimal),而且是逐个元素的比较。

如下:

import numpy as np
from numpy.testing import assert_array_almost_equal

if __name__ == '__main__':
    a = np.arange(6).reshape(2,3)
    print(a,a.sum(0))
    b = a - 1e-5
    print(b)
    assert_array_almost_equal(a,b,decimal=6)

输出:

[[0 1 2]
 [3 4 5]] [3 5 7]
[[-1.00000e-05  9.99990e-01  1.99999e+00]
 [ 2.99999e+00  3.99999e+00  4.99999e+00]]
AssertionError: 
Arrays are not almost equal to 6 decimals

Mismatched elements: 6 / 6 (100%)
Max absolute difference: 1.e-05
Max relative difference: 1.
 x: array([[0, 1, 2],
       [3, 4, 5]])
 y: array([[-1.00000e-05,  9.99990e-01,  1.99999e+00],
       [ 2.99999e+00,  3.99999e+00,  4.99999e+00]])

参考:numpy.testing.assert_array_almost_equal — NumPy v1.22 Manualicon-default.png?t=M3C8https://numpy.org/doc/stable/reference/generated/numpy.testing.assert_array_almost_equal.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值