3

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.

gamerx
  • 579
  • 5
  • 16
  • 1
    Assign-mathematical operators of an array with a view of itself may not work as expected. See likely duplicate [Unexpected result with += on NumPy arrays](https://stackoverflow.com/q/26278241) (`x[2:] = x[2:] + x[:-2]` or `x[2:] += x[:-2].copy()` should work reliably). – jdehesa Jan 16 '19 at 12:25

1 Answers1

0

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.])
Filipe Aleixo
  • 3,924
  • 3
  • 41
  • 74
  • 1
    I suspect it's specific to numpy version 1.11.3. Even after restarting my kernel, I get the same issue. However, I get the expected output when I run the exact same code in another environment using a later numpy version. – gamerx Jan 16 '19 at 12:01