numpy.array_equal返回False,即使数组具有相同的形状和值 [英] numpy.array_equal returns False, even though arrays have the same shape and values

查看:618
本文介绍了numpy.array_equal返回False,即使数组具有相同的形状和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的功能,如下所示

I have a very simple function, as shown below

def new_price(A, B, x):
    return np.linalg.inv(A @ B) @ x

这些是我给它的输入

A = np.array([
    [2, 0, 1, 0],
    [1, 1, 1, 1],
    [0, 0, 0, 10]
]) 

B = np.array([
    [3, 3, 3],
    [2, 0, 8],
    [0, 5, 3],
    [0, 0, 10] 
])

x = np.array([ 84, 149, 500])

这将返回数组[ 1. 3. 5.].但是,当我进行以下相等检查时,它返回False

This returns the array [ 1. 3. 5.]. But, when I make the following equality check, it returns False

v1 = new_price(A, B, x)
v2 = np.array([1.0, 3.0, 5.0])
np.array_equal(new_price(A, B, [ 84, 149, 500]), np.array([1.0, 3.0, 5.0]))

我检查了两个数组的形状和类型相同.我在这里想念什么?

I checked and the shapes and the types of both the arrays are same. What am I missing here?

推荐答案

不完全相同:

>>> new_price(A, B, [ 84, 149, 500]) -  np.array([1, 3, 5])
array([  2.84217094e-14,  -1.42108547e-14,   0.00000000e+00])

更好地使用np.allclose():

>>> np.allclose(new_price(A, B, [ 84, 149, 500]), np.array([1.0, 3.0, 5.0]))
True

如果两个数组在公差范围内按元素方式相等,则返回True.

Returns True if two arrays are element-wise equal within a tolerance.

您可以调整相对公差和绝对公差.

You can adjust the relative and absolute tolerance.

对于很小的值仍然适用:

Still true for really small values:

>>> np.allclose(new_price(A, B, [ 84, 149, 500]), np.array([1.0, 3.0, 5.0]),
                atol=1e-13, rtol=1e-14)
True

找到了极限:

>>> np.allclose(new_price(A, B, [ 84, 149, 500]), np.array([1.0, 3.0, 5.0]),
                atol=1e-14, rtol=1e-14)
False

这篇关于numpy.array_equal返回False,即使数组具有相同的形状和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆