'While loop incorrectly updating the variables [duplicate]
I have a while loop in my python code which contains a nested for loop that loops over a 2D array.
The variable T needs to get updated at end of the while loop.
However I'm seeing that the variable is getting updated within the for loop itself.
What am I doing incorrectly here and how to modify this?
error = 1
tolerance = 1e-6
T = T_new
itr = 0
while error>tolerance:
itr = itr+1
for i in range(1,imax-1):
for j in range(1,jmax-1):
T_new[i,j]=0.25*(T[i-1,j]+T[i+1,j]+T[i,j-1]+T[i,j+1])
error = np.max(np.abs(T_new-T))
T = T_new
Solution 1:[1]
In python, only primitives: ints, floats, strings, are copied by value. Lists, dicts, and objects by default are copied by reference.
You can from copy import deepcopy and use T = deepcopy(T_new) to get the behavior you want. Before doing so though, think about if you are writing your code in an optimal manner. For example, you use itr = itr + 1 instead of itr += 1. Also think about formatting. Use an auto formatter if you can't bother to write your code properly.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Elijah |
