Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

- vs -= operators with numpy

Tags:

python

numpy

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]

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]

Then everything works flawlessly.

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

which again works as expected, producing [2 3] [2 3] at both print statements.

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.

Thanks for any help!

like image 944
Josh Avatar asked Jan 28 '12 17:01

Josh


People also ask

Can I use += with NumPy?

In numpy, += is implemented to do in memory changes, while + returns a new array.

What is the operator used for in NumPy?

In NumPy, the @ operator means matrix multiplication. If you are familiar with matrix multiplication, I'm sure this answers your questions.

Does Rpy work with NumPy?

rpy2 has features to ease bidirectional communication with numpy .


1 Answers

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
like image 53
Fred Foo Avatar answered Oct 12 '22 07:10

Fred Foo