求解有解的线性方程组;
代码实现:
高斯消元法:
import numpy as npdef 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添加置列表Xfor 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 XA = np.array([[3,1,-1,4],[4,0,4,8],[12,-3,3,9]]) print(Gauss_elimination(A))
列主元高斯消去法 :
import numpy as numpydef 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)<abs(A[i][k])): max=A[i][k]x=i #记录选择交换的行数A[[k,i],:]=A[[i,k],:]return Gauss_elimination(A)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]) 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 XA = np.array([[3,1,-1,4],[4,0,4,8],[12,-3,3,9]])print(Gauss_Lelimination(A))
全主元高斯消去法:
import numpy as numpydef 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)<abs(A[i][j])): #选去绝对值最大者作为主元max=A[i][j]x=i #记录选择交换的行数y=j #记录选择交换的列数A[[k,x],:]=A[[x,k],:] #交换第k行和第x行A[:,[k,y]]=A[:,[y,k]] #交换第k列和第y列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]) 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 XA = np.array([[0.007,-0.8,0.7],[-0.1,10,10]]) print(Gauss_Qelimination(A))
运行结果:
[1.0, 1.75, 0.75]
[1.0, 2.0, 1.0]
[-14.0, -1500.0]