目录
例子
自编程具体过程见文章数值计算——列主元高斯消去法求解线性方程组(附代码)_hser-chen的博客-CSDN博客
python代码
#Copyright , 2021, Co., Ltd.
#File name: Solve_linear_equations.py // 文件名
#Author: chenshuai Version: v1 Date: 20210423
#Description: // 自编程与numpy函数库求解线性方程组对比
import numpy as np
import pandas as pd
totall = np.loadtxt('B.txt')
n=totall.shape[0]
A=totall[0:n,0:n]
B=totall[0:n,n]
def cpe_gaussian_elimination(a,b):
#n-1步消元
epslion=0.01
n=a.shape[0]
x=[0 for x in range(n)]
mi_k=[0 for x in range(n)]
for k in range(n-1):
if a[k][k]==0 or abs(a[k][k])<epslion:
#//列主元的条件就是主元为0或者主元小于某一个值
max = abs(a[k][k])
for i in range(k,n):
if max<abs(a[i][k]):
max = abs(a[i][k])
for i in range(k,n):
if max==abs(a[i][k]):
for j in range(k,n):
c=a[k][j]
a[k][j]=a[i][j]
a[i][j]=c
c=b[k]
b[k]=b[i]
b[i]=c
for j in range(k+1,n):mi_k[j]=a[j][k]/a[k][k]
for i in range(k+1,n):
for j in range(k,n):
a[i][j]=a[i][j]-mi_k[i]*a[k][j]
b[i]=b[i]-mi_k[i]*b[k]
#回代过程
x[n - 1] = b[n - 1] / a[n - 1][n - 1]
for i in range(n-2,-1,-1):
sum=0
for j in range(i+1,n):
sum+=a[i][j]*x[j]
x[i]=(b[i]-sum)/a[i][i]
return x
print("numpy函数求解: {}".format(np.linalg.solve(A,B))) #numpy的线性方程组求解函数
print("自编程函数求解: {}".format(cpe_gaussian_elimination(A,B))) #自编程线性方程组求解函数
输出结果