-vs-=使用numpy的运算符 [英] - vs -= operators with numpy
问题描述
我的python代码中有一些与-
和-=
相关的奇怪行为.我正在使用numpy编写QR分解,并在双循环中包含以下代码行:
I'm having some strange behavior in my python code related to -
and -=
. I'm writing a QR decomposition using numpy, and have the following line of code in a double loop:
v = v - r[i,j] * q[:,i]
其中q
和r
都是numpy.array
,而v
是另一个numpy.array
的切片,作为v = x[:,j]
.
where q
and r
are both numpy.array
, and v
is a slice of another numpy.array
taken as v = x[:,j]
.
上面的代码并非在所有情况下都能正常工作.但是,如果我进行以下更改:
The above code doesn't work as expected in all cases. However, if I make the following change:
v -= r[i,j] * q[:,i]
然后一切都完美无瑕.
我的印象是这两行应该是相同的.为了测试-=
和_ = _ -
的工作方式是否不同,我创建了以下代码段
I was under the impression that those two lines should be identical. To test whether -=
and _ = _ -
were working differently, I created the following snippet
import numpy
x = numpy.array(range(0,6))
y = numpy.array(range(0,6))
u = x[3:5]
v = y[3:5]
print u,v
u = u - [1,1]
v -= [1,1]
print u,v
再次按预期工作,在两个打印语句中均生成[2 3] [2 3]
.
which again works as expected, producing [2 3] [2 3]
at both print statements.
所以我很困惑为什么这两行表现不同.我唯一想到的可能是我有时要处理极小的数字(数量级为10 ^ -8或更小),并且存在一些-=
更好的精度问题?随着x
的元素变小,第一行的性能越来越差.
So I'm entirely confused why those two lines perform differently. The only possible thing I can think of is that I am dealing with extremely small numbers sometimes (on the order of 10^-8 or smaller) and there is some precision issue that -=
is better at? The first line performs increasingly worse as the elements of x
get smaller.
对于是否有与此类似的问题还有其他帖子,我深表歉意,我无法搜索-
和-=
,而且我不知道除任务分配/操作员之外是否还有其他正确的用语.
I apologize if there's any other posts about this similar issue, I can't search for -
and -=
and I don't know if there's any correct terms for these besides assignment/operators.
感谢您的帮助!
推荐答案
当v
是切片时,v -= X
和v = v - X
会产生非常不同的结果.考虑
When v
is a slice, then v -= X
and v = v - X
produce very different results. Consider
>>> x = np.arange(6)
>>> v = x[1:4]
>>> v -= 1
>>> v
array([0, 1, 2])
>>> x
array([0, 0, 1, 2, 4, 5])
其中v -= 1
更新切片,并因此更新其查看的数组.
where v -= 1
updates the slice, and therefore the array that it views, in-place, vs.
>>> x = np.arange(6)
>>> v = x[1:4]
>>> v = v - 1
>>> v
array([0, 1, 2])
>>> x
array([0, 1, 2, 3, 4, 5])
其中,v = v - 1
重置变量v
,同时保持x
不变.要在没有-=
的情况下获得前一个结果,您必须
where v = v - 1
resets the variable v
while leaving x
untouched. To obtain the former result without -=
, you'd have to do
v[:] = v - 1
这篇关于-vs-=使用numpy的运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!