Dawnx
Dawnx

Reputation: 1

Python in-place operator (as "+="), numpy array and identity function not working properly?

The arrays yn and zn are equals numericaly speaking, but there is an odd difference: the line yn += 7, as expected, does not change tn array, but the second last line zn += 7 changes tn array!

This is the code:

import numpy as np
def f(x): return (1*x)
def g(x): return (x)
nn = 5
tn = np.zeros(nn)
yn = np.zeros(nn)
zn = np.zeros(nn)

tn = np.linspace(0,1,nn)
yn = f(tn)
zn = g(tn)

print('tn at step1 =',tn)
yn += 7  #as expected, this line does not change tn.
print('tn at step2 =',tn)
zn += 7  #why this line adds 7 to tn array?!
print('tn at step3 =',tn)

The output is:

tn at step1 = [ 0.    0.25  0.5   0.75  1.  ]
tn at step2 = [ 0.    0.25  0.5   0.75  1.  ]
tn at step3 = [ 7.    7.25  7.5   7.75  8.  ] *why is 7 added to tn array?!*

Notice that are involved:

Although I have solved this problem using zn = zn + 7 instead zn += 7 my question is: why in the second last line zn += 7 changes tn array?

Upvotes: 0

Views: 235

Answers (1)

zondo
zondo

Reputation: 20336

When you define g(), you make it return its argument unchanged. Because of that, when you say zn = g(tn), you are in effect saying zn = tn. Therefore, zn is now just another name for tn. The += operator is not quite the exact duplicate of x = x +. It generally does the same thing, but in the background it is calling a method named __iadd__. Since zn and tn are now the same object, you are calling tn's __iadd__ method. Because of that, tn is modified. To change that, you could say zn = tn.copy() when you first define it; or you could say zn = zn + 7 when you try to add 7.

Upvotes: 7

Related Questions