在高斯消除中如何获得矩阵的解

时间:2018-09-22 17:53:09

标签: python python-3.x

A=[[1,1,8],[2,-1,1]]
def triangular(A):


    n = len(A) 
    for i in range(n):

        pivot = A[i][i]
        for j in range(i+1, n): 
            m = -A[j][i]/pivot
            for k in range(i, n+1): 
                A[j][k] += m*A[i][k]
def substitui(A):
    n = len(A) 
    x = n*[0] 
    for i in range(n-1, -1, -1):

        s = sum([A[i][j]*x[j]
        for j in range(i+1,n)])
        x[i] = (A[i][n] - s)/A[i][i]
        return x


def resolve(A):

    triangular(A)
    x = substitui(A)
    return x

print(resolve(A))

如何获得该矩阵A的解?我不明白为什么会出错,解决方案是给x = [0,5]而不是x = [3,5]。有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

您犯了一个简单的错误。在substitui中,行return x不应位于for循环中。您应该取消缩进:

def substitui(A):
    n = len(A) 
    x = n*[0] 
    for i in range(n-1, -1, -1):
        s = sum([A[i][j]*x[j]
        for j in range(i+1,n)])
        x[i] = (A[i][n] - s)/A[i][i]
    return x  # like this