1

I tried to make a random symmetric matrix to test my program. I don't care about the data at all as long as it is symmetric (sufficient randomness is no concern at all).

My first attempt was this:

x=np.random.random((100,100))
x+=x.T

However, np.all(x==x.T) returns False. print x==x.T yields

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)

I tried to run a small test example with n=10 to see what was going on, but that example works just as you would expect it to.

If I do it like this instead:

x=np.random.random((100,100))
x=x+x.T

then it works just fine.

What's going on here? Aren't these statements semantically equivalent? What's the difference?

4

1 回答 1

2

这些语句在语义上并不等效。 x.T返回原始数组的视图。在这种+=情况下,您实际上是在x迭代时更改 的值(这会更改 的值x.T)。

这样想......当你的算法到达 index(3,4)时,它在伪代码中看起来像这样:

x[3,4] = x[3,4] + x[4,3]

现在,当您的迭代达到 时(4,3),您会这样做

x[4,3] = x[4,3] + x[3,4]

但是,x[3,4]不是你开始迭代时的样子。


在第二种情况下,您实际上创建了一个新(空)数组并更改空数组中的元素(从不写入x)。所以伪代码看起来像:

y[3,4] = x[3,4] + x[4,3]

y[4,3] = x[4,3] + x[3,4]

这显然会给你一个对称矩阵 ( y.

于 2013-06-13T15:46:13.103 回答