Reputation: 21
Super New to programming and still learning how to debug. Every time I run this program for Gauss elimination I get
"line 16, in GaussElim tmp=A[maxRow][k] IndexError: list index out of range"
I think it mean the code is stepping over the limit of the index, but I am not sure on how to correct it. Any advice would be much appreciated thank you!
def GaussElim(A):
n=len(A)
for i in range(0,n): #search for maximum in this column
maxE1=abs(A[i][i])
maxRow=i
for k in range(i+1,n):
if abs(A[k][i])>maxE1:
maxE1=abs(A[k][i])
maxRow=k
# swap maximum row with current row (column by column)
for k in range(i,n+1):
tmp=A[maxRow][k]
A[maxRow][k]=A[i][k]
A[i][k]=tmp
for k in range(i+1,n):
c=-A[k][i]/A[i][i]
for j in range(i,n+1):
if i==j:
A[k][j]=0
else:
A[k][j]+=c*A[i][j]
#solve equation Ax+b for an upper triangular matrix A
x=[0 for i in range(n)]
for i in range(n-1,-1,-1):
x[i]=A[i][n]/A[i][i]
for k in range(i-1,-1,-1):
A[k][n]-=A[k][i]*x[i]
return x
def main():
A=[[2,7,3,6,2],
[3,3,4,4,6],
[6,9,5,3,3],
[6,9,5,3,3],
[4,2,1,7,5]]
mysum1 = GaussElim(A)
print('a) GaussElimination Solution = {:.1f}'.format(mysum1))
Upvotes: 2
Views: 3917
Reputation: 931
In python, lists are zero indexed. If you print the value of k, you'll see you're getting a value k=5, which is presumably coming from your range(i, n+1) (where n=5). Your 5x5 array will only support indexing from 0 to 4.
Upvotes: 0