高斯消元法的Python实现

# coding: utf8
import numpy as np


# 设置矩阵
def getInput():
    matrix_a = np.mat([[2, 3, 11, 5],
                     [1, 1, 5, 2],
                     [2, 1, 3, 2],
                     [1, 1, 3, 4]],dtype=float)
    matrix_b = np.mat([2,1,-3,-3])
    #答案:-2 0 1 1
    return matrix_a, matrix_b

def SequentialGauss(mat_a):
    for i in range(0, (mat_a.shape[0])-1):
        if mat_a[i, i] == 0:
            print("终断运算:")
            print(mat_a)
            break
        else:
            for j in range(i+1, mat_a.shape[0]):
                mat_a[j:j+1 , :] = mat_a[j:j+1,:] - \
                                                    (mat_a[j,i]/mat_a[i,i])*mat_a[i, :]
    return mat_a


# 回带过程
def revert(new_mat):
    #创建矩阵存放答案 初始化为0
    x = np.mat(np.zeros(new_mat.shape[0], dtype=float))
    number = x.shape[1]-1
    # print(number)
    b = number+1
    x[0,number] = new_mat[number,b]/new_mat[number, number]
    for i in range(number-1,-1,-1):
        try:
            x[0,i] = (new_mat[i,b]-np.sum(np.multiply(new_mat[i,i+1:b],x[0,i+1:b])))/(new_mat[i,i])
        except:print("错误")
    print(x)
if __name__ == "__main__":
    mat_a, mat_b = getInput()
    # 合并两个矩阵
    print("原矩阵")
    print(np.hstack((mat_a, mat_b.T)))
    new_mat = SequentialGauss(np.hstack((mat_a, mat_b.T)))
    print("三角矩阵")
    print(new_mat)
    print("方程的解")
    revert(new_mat)

运行结果如下:

高斯消元法的Python实现_第1张图片

 

 

你可能感兴趣的:(python)