超级新手编程,仍在学习如何调试。每次我运行这个程序进行高斯消除时,我都会得到
“第 16 行,在 GaussElim tmp=A[maxRow][k] IndexError: list index out of range”
我认为这意味着代码超出了索引的限制,但我不确定如何纠正它。任何建议将不胜感激,谢谢!
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))