Reputation: 83
The given code below is a part of a code i am working on. Here x
is a numpy array and f is an array of arrays as given in the example below the code. i have to update all values of the array x
and thus i use run a loop to do so. I am using an iterative scheme and the values are updated using the last known value of x
. However the loop runs fine for the first time, but the next time it takes the value of x
that it got when the 1st loop was run. But i intend to take the old value of x
for all the loops. Can anyone help me out please?
import numpy as np
def mulsucc(x0,f,n):
old=x0
for k in range(1,100):
for i in range(0,n):
print "old" + str(old)
x0[i]=np.sum(old*(f[i][0:len(f[i])-1])) + 2
print "new" + str(x0)
return x0
x0=np.array([0,0])
f=np.array([[4,5,-20],[2,7,-10]])
print mulsucc(x0,f,2)
the output comes out to be:
old[0 0]
new[2 0]
old[2 0]
new[2 6]
[2 6]
however I want that the second old value should also be [0 0]
.
Upvotes: 2
Views: 129
Reputation: 2016
you should change:
old = x0
to:
old = x0.copy()
if you want to keep old
unchanged. The problem here is that old
and x0
are pointers to the same object, so when you alter x0
with the line:
x0[i]=np.sum(old*(f[i][0:len(f[i])-1])) + 2
you are also altering old
. old is x0
will be True
.
There is more to it if you want to dig a bit into related topic.
Upvotes: 1