- vs -= operators with numpy

前端 未结 3 1096
闹比i
闹比i 2021-01-04 02:55

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 o

3条回答
  •  旧巷少年郎
    2021-01-04 03:08

    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])
    

    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])
    

    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
    

提交回复
热议问题