+= 在 NumPy 数组上出现意外结果 [英] Unexpected result with += on NumPy arrays

查看:29
本文介绍了+= 在 NumPy 数组上出现意外结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 NumPy 在 Python 中使用标准方法创建对称矩阵/数组:

I am creating symmetric matrices/arrays in Python with NumPy, using a standard method:

x = rand(500,500)
x = (x+x.T)
all(x==x.T)
> True

现在让我们聪明一点:

x = rand(500,500)
x += x.T
all(x==x.T)
> False

等等,什么?

x==x.T
> array([[ True,  True,  True, ..., False, False, False],
       [ True,  True,  True, ..., False, False, False],
       [ True,  True,  True, ..., False, False, False],
       ..., 
       [False, False, False, ...,  True,  True,  True],
       [False, False, False, ...,  True,  True,  True],
       [False, False, False, ...,  True,  True,  True]], dtype=bool)

左上和右下部分是对称的.如果我选择较小的阵列会怎样?

The upper left and lower right segments are symmetrical. What if I chose a smaller array?

x = rand(50,50)
x += x.T
all(x==x.T)
> True

好的....

x = rand(90,90)
x += x.T
all(x==x.T)
> True

x = rand(91,91)
x += x.T
all(x==x.T)
> False

为了确定...

x = rand(91,91)
x = (x+x.T)
all(x==x.T)
> True

这是一个错误,还是我要学习一些关于 += 和 NumPy 数组的疯狂知识?

Is this a bug, or am I about to learn something crazy about += and NumPy arrays?

推荐答案

transpose 操作 返回数组的视图,这意味着没有分配新的数组.反过来,这意味着您正在同时读取和修改数组.很难说为什么结果的某些大小或某些区域有效,但很可能与 numpy 如何处理数组加法(也许它制作子矩阵的副本)和/或数组视图(也许对于它确实创建的小尺寸)有关一个新数组).

The transpose operation returns a view of the array, which means that no new array is allocated. Which, in turn, means that you are reading and modifying the array at the same time. It's hard to tell why some sizes or some areas of the result work, but most likely it has to do with how numpy deals with array addition (maybe it makes copies of submatrices) and/or array views (maybe for small sizes it does create a new array).

x = x + x.T 操作有效,因为您正在创建一个新数组,然后分配给 x,当然.

The x = x + x.T operation works because there you are creating a new array and then assigning to x, of course.

这篇关于+= 在 NumPy 数组上出现意外结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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