Unexpected result with += on NumPy arrays

前端 未结 3 1254
野性不改
野性不改 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 problem is that the addition is not done "at once"; x.T is a view of the x so as you start adding to each element of x, x.T is mutated. This messes up later additions.

    The fact it works for sizes below (91, 91) is almost definitely an implementation detail. Using

    x = numpy.random.rand(1000, 1000)
    x += x.T.copy()
    numpy.all(x==x.T)
    #>>> True
    

    fixes that, but then you don't really have any space-benefit.

提交回复
热议问题