在numpy中生成对称矩阵的语义 [英] semantics of generating symmetric matrices in numpy
问题描述
我试图制作一个随机对称矩阵来测试我的程序.只要对称,我就根本不在乎数据(完全没有随机性).
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).
我的第一次尝试是
x=np.random.random((100,100))
x+=x.T
但是,np.all(x==x.T)
返回False. print 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)
我尝试运行一个n = 10的小型测试示例,以了解发生了什么,但是该示例可以正常运行.
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.
如果我改为这样做:
x=np.random.random((100,100))
x=x+x.T
然后就可以了.
这是怎么回事?这些语句在语义上不是等效的吗?有什么区别?
What's going on here? Aren't these statements semantically equivalent? What's the difference?
推荐答案
这些语句在语义上并不等效. x.T
返回原始数组的 view .在+=
情况下,实际上是在遍历x
时更改了x
的值(这会更改x.T
的值).
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
).
这样想吧...当您的算法索引到(3,4)
时,它在伪代码中看起来像这样:
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]
现在,当您迭代到(4,3)
时,您便会
now, when your iteration gets to (4,3)
, you do
x[4,3] = x[4,3] + x[3,4]
但是,x[3,4]
不是您开始迭代时的样子.
but, x[3,4]
is not what it was when you started iterating.
在第二种情况下,您实际上创建了一个新的(空)数组并更改了空数组中的元素(切勿写入x
).因此,伪代码如下所示:
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]
和
y[4,3] = x[4,3] + x[3,4]
这显然会给您一个对称矩阵(y
.
which obviously will give you a symmetric matrix (y
.
这篇关于在numpy中生成对称矩阵的语义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!