高斯消去法(Gauss-Jordan方法)的Python实现
作者:互联网
高斯消去法的改进形式为Gauss-Jordan Elimination Method,要求每一行的主元素所在列元素全部消去为0,除了主元素本身。区别如下:
代码实现如下:
# -*- coding: utf-8 -*- # @Author : ZhaoKe # @Time : 2022-09-05 23:34 from typing import List # input a augmented matrix, output its simpler form def GaussJordanMethod(matrix: List[List]) -> List[List]: PREC = 3 m, n = len(matrix), len(matrix[0]) # from left to right for j in range(n): # 主元素为0的话,要交换行令这一行主元素不为0 if j >= m: break if matrix[j][j] == 0: for k in range(j + 1, m): if matrix[k][j] == 0: continue else: matrix[j], matrix[k] = matrix[k], matrix[j] print(matrix) break # from above to bottom # 为了实现Gauss-Jordan,pivot位置的元素应该置为1 fac = matrix[j][j] for l in range(0, n): matrix[j][l] = matrix[j][l] / fac # 不再拘泥于对角线下方消除,整整一列都要消除 for i in range(m): # 主元素不可以消去,直接跳过该行 if i == j: continue # 当前行的该列元素为0的话,不必执行消去步骤,跳过即可 if matrix[i][j] == 0: continue # replace the jth equation by a combination of itself plus a multiple of the ith equation coef = matrix[i][j] for k in range(n): matrix[i][k] = round(matrix[i][k] - coef * matrix[j][k], PREC) print(matrix[i]) # elimination end print(matrix) # solution as follow for i in range(m - 1, -1, -1): for j in range(n - 1, -1, -1): if matrix[i][j] == 0: continue else: print("x" + str(i+1), "=", matrix[i][-1]) break return matrix if __name__ == '__main__': # input_m0 = [[2, 1, 1, 1], [6, 2, 1, -1], [-2, 2, 1, 7]] # 结果正确 # input_m1 = [[0, 1, -1, 3], [-2, 4, -1, 1], [-2, 5, -4, -2]] # 结果正确 input_m2 = [[2, 2, 6, 4], [2, 1, 7, 6], [-2, -6, -7, -1]] # 结果正确 GaussJordanMethod(input_m2) # 病态方程: # input_m3 = [[47, 28, 19], [89, 53, 36]] # 该程序暂不适合病态方程的数值计算,另开随笔研究该问题 # GaussJordanMethod(input_m3)
经验证该程序正确
标签:__,matrix,Python,元素,List,Gauss,range,input,消去法 来源: https://www.cnblogs.com/zhaoke271828/p/16660295.html