2

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].

2
  • The k loop is not "used" since you do a return after the i loop. Is that on purpose? Commented Nov 5, 2015 at 14:49
  • It is a part of a bigger code.. so actually i forgot to remove the k loop.. the problem i face is currently only concerned with the i loop.. Commented Nov 5, 2015 at 14:53

1 Answer 1

1

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.

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.