Numpy: Output from adding sub-array to itself

Viewed 34

Wonder what is the logic behind this numpy output. Basically I'm trying to add a subset of a numpy array to itself via slicing with the following code.

x = np.zeros((10,))
x[:3] += 1
print x
x[2:] += x[:-2]
print x

Original x:

[ 1.  1.  1.  0.  0.  0.  0.  0.  0.  0.]

Expected output:

[ 1.  1.  2.  1.  1.  0.  0.  0.  0.  0.]

However it returns me the following result, which is totally unexpected. Anybody knows what is the logic here?

Actual output:

[ 1.  1.  2.  1.  2.  1.  2.  1.  2.  1.]

Edit: Issue seems specific to numpy 1.11.3. Tried it again on an environment with numpy 1.15.4 and it returns the expected output.

1 Answers

Using your code, I'm getting the expected output:

x = np.zeros((10,))

x[:3] += 1

x
array([1., 1., 1., 0., 0., 0., 0., 0., 0., 0.])

x[2:] += x[:-2]

x
array([1., 1., 2., 1., 1., 0., 0., 0., 0., 0.])
Related