Unexpected result with += on NumPy arrays

前端 未结 3 1256
野性不改
野性不改 2020-12-10 01:13

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

3条回答
  •  一生所求
    2020-12-10 02:00

    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.

提交回复
热议问题