超级新编程,仍然学习如何调试。每次我运行这个程序进行高斯消除时我都会得到
"第16行,在GaussElim中 TMP = A [MaxRow的] [k]的 IndexError:列表索引超出范围"
我认为这意味着代码踩到了索引的极限,但我不确定如何纠正它。非常感谢任何建议,谢谢!
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))
答案 0 :(得分:0)
在python中,列表是零索引的。如果您打印k的值,您将看到您获得的值k = 5,这可能来自您的范围(i,n + 1)(其中n = 5)。您的5x5阵列仅支持从0到4的索引。