Python 實現順序高斯消元法示例
阿新 • • 發佈:2020-01-09
我就廢話不多說,直接上程式碼吧!
# coding: utf8 import numpy as np # 設定矩陣 def getInput(): matrix_a = np.mat([[2,3,11,5],[1,1,5,2],[2,4]],dtype=float) matrix_b = np.mat([2,-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 實現順序高斯消元法示例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。