semantics of generating symmetric matrices in numpy

邮差的信 提交于 2019-12-14 02:46:32

问题


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?


回答1:


Those statements aren't semantically equivalent. x.T returns a view of the original array. in the += case, you're actually changing the values of x as you iterate over it (which changes the values of x.T).

Think of it this way ... When your algorithm gets to index (3,4), it looks something like this in pseudocode:

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

now, when your iteration gets to (4,3), you do

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

but, x[3,4] is not what it was when you started iterating.


In the second case, you actually create a new (empty) array and change the elements in the empty array (never writing to x). So the pseudocode looks something like:

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

and

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

which obviously will give you a symmetric matrix (y.



来源:https://stackoverflow.com/questions/17091285/semantics-of-generating-symmetric-matrices-in-numpy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!