0

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:

  • numpy array
  • g(x) as identity function
  • in-place iadd operator (+=)

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?

1
  • A couple of coding points. The initial zeros definitions of tn etc are overwritten by later assignments. you don't need them. In g, the () doesn't add anything. Use return x, or as recommended in the answer return x.copy(). Commented Feb 20, 2016 at 20:38

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.