I am trying to reduce a matrix to its echlon form using a function but upon the calling the function, it is also changing its arguments. Here is the code
def GaussE(E,r):
N = np.size(r)
for i in range(0,N-1):
for j in range(i+1,N):
f=(E[j,i]/E[i,i])
r[j]= r[j] -(f)*r[i]
for k in range(i,N):
E[j,k] = E[j,k]-(f*E[i,k])
return(E,r)
A = np.array([[5.10,8.70],[2.40,4.10]])
b = np.array([9.48,4.48])
print(A,b)
output: [[ 5.1 8.7] [ 2.4 4.1]] [ 9.48 4.48]
X = GaussE(A[:],b[:])
print(A,b) # Why is A and b changing? they should not change
output:[[ 5.10000000e+00 8.70000000e+00] [ 0.00000000e+00 5.88235294e-03]] [ 9.48 0.01882353]
In python every variable refers to an object. It refers to the object pointer so it is using the object itself.
In that function you are referencing E
like E[j,k]
and r
like r[j]
and assigning to it which means you are using that same object and means you are manipulating it.
Try to use copy
at the first of your function (from copy import copy
)
from copy import copy
def GaussE(E,r):
E = copy(E)
r = copy(r)
N = np.size(r)
for i in range(0,N-1):
for j in range(i+1,N):
f=(E[j,i]/E[i,i])
r[j]= r[j] -(f)*r[i]
for k in range(i,N):
E[j,k] = E[j,k]-(f*E[i,k])
return(E,r)
A = np.array([[5.10,8.70],[2.40,4.10]])
b = np.array([9.48,4.48])
print(A,b)