高斯消元法、列主元高斯消去法、全主元高斯消去法Python实现

求解有解的线性方程组;

代码实现:

高斯消元法:

import numpy as np
def Gauss_elimination(A): 
    # 高斯消去法求解
    # 消元,化为上三角
    for k in range(len(A[0])):      
        for i in range(k+1,len(A)):      
            m=A[i][k]/A[k][k]
            for j in range(k,len(A[0])):     
                A[i][j]-=m*A[k][j]
    #回代
    X=[]     #设置空列表X来存储方程组的解x1,x2,...
    X.append(A[len(A)-1][len(A[0])-1]/A[len(A)-1][len(A[0])-2])     #将所得的xn添加置列表X
    for i in range(len(A)-2,-1,-1):     
        s=A[i][len(A[0])-1]   
        for j in range(i+1,len(A)):
                s = s - A[i][j] * X[len(A)-1-j]     
        X.append(s/A[i][i])      
    X.reverse()     
    return X

A = np.array([[3,1,-1,4],[4,0,4,8],[12,-3,3,9]])    
print(Gauss_elimination(A))

列主元高斯消去法 :

import numpy as numpy
def Gauss_Lelimination(A):  
    # 列主元高斯消去法求解
    for k in range(len(A[0])-1):  
        # 在整个系数矩阵中选择列主元
        max=A[k][k]
        for i in range(k+1,len(A)):  
            # 选主元
            if (abs(max)

全主元高斯消去法: 

import numpy as numpy
def Gauss_Qelimination(A):
    # 全主元高斯消去法求解
    for k in range(len(A[0])-1):
        max=A[k][k]
        for i in range(k,len(A)):
            for j in range(k,len(A[0])-1):
                if (abs(max)

运行结果:

[1.0, 1.75, 0.75]
[1.0, 2.0, 1.0]
[-14.0, -1500.0]

你可能感兴趣的:(数值分析练习,python,numpy,机器学习)