Blade Blade - 1 month ago 36
Python Question

python: variable in while loop

I'm running the following code in python:

w= np.random.rand(3)


while (np.linalg.norm(w - w_old)) / np.linalg.norm(w) > 1e-5:


print w
print w_old


print w
print w_old

The results for the prints are :

[ 0.22877423 0.59402658 0.16657174]

[ 0.22877423 0.59402658 0.16657174]


[ 0.21625852 0.5573612 0.123111 ]

[ 0.21625852 0.5573612 0.123111 ]

I'm wondering why the value of w_old has been changed? Shouldn't it be updated after going back to the beginning of the while loop? How can I fix this?

Answer Source

Just using

w_old = w

doesn't copy w, using = just tells python that you want another name for whatever is stored in w. So every in-place change to w will also change w_old. There is a really nice blog post about it in case you want more details Ned Batchelder: "Facts and myths about Python names and values"

You can explicitly copy a numpy array, for example, using the copy method:

w_old = w.copy()