Using opt.root, I want to store the arguments with which the function is called.
import scipy.optimize as opt
x0=[0, 0]
prev_x=x0
count=0
def fun(x):
global prev_x,count
print('---')
print('iteration',count)
count+=1
print('last iteration',prev_x)
print('this iteration',x)
prev_x=x
return x[0]**2*x[1]+1,x[1]-x[0]+2
result=opt.root(fun,x0,method='lm')
I would expect that for every iteration step, the values saved in last_x should match the current value of the previous iteration. Running the above code, I get different values between e.g. iterations 8 and 9.
Am I missing something fundamental about the behavior of Python and/or SciPy, or is this a bug?
[edit] I shortened the question to the essential point.
assigning lists does not copy values across, just gives it a different name, so changes to the list through one name are reflected in the other. To get the behavior you expect, change the relevant line to
prev_x=x.copy()
(note the copy()
bit)