Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
141 views
in Technique[技术] by (71.8m points)

python - Unexpected result with += on NumPy arrays

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

Now let's be clever:

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

Wait, what?

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

OK....

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

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

And just to be sure...

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...