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 实现顺序高斯消元法示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。