import numpy as np
# 合并A、b,增广矩阵AB
class gauss:
def __init__(self, A: list, b_T: list):
'''
:param A: 矩阵A,n*n
:param b_T: 常数项b的转置,n
'''
self.A = np.array(A)
self.b_T = np.array(b_T)
self.__n = len(self.b_T)
# 用于保存返回值
self.x = np.zeros(self.__n)
def xiao_yuan(self):
'''
消去过程
:return:
'''
b = self.b_T.reshape(-1, 1)
# reshape(-1, 1) 转换成一列
AB = np.column_stack((self.A, b))
# 将A、b合并成增广矩阵AB
for k in range(1, self.__n + 1):
for i in range(k, self.__n):
'''
这个循环内操作的矩阵,实际上被限制为原始矩阵截去前k行
外层循环:k=1
'''
m = -AB[i][k - 1] / AB[k - 1][k - 1]
AB[i] += AB[k - 1] * m
# m乘方程式两边第一行加到第i行
else:
# print(f'第{k}次\n', AB)
pass
else:
# 循环结束,重新对A、b_T进行赋值
AB_T = AB.transpose()
# 将AB 进行转置,用于重新拆分出A 和 b_T
self.A = (AB_T[:len(AB_T) - 1]).transpose()
self.b_T = AB_T[-1]
def hui_dai(self):
'''
回代过程
:return:
'''
def sum_ax(k: int):
sum2 = 0.0
for q in range(k + 1, self.__n):
sum2 += (self.A[k][q] * self.x[q])
return float(sum2)
for j in range(self.__n - 1, -1, -1):
if j == self.__n - 1:
self.x[j] = self.b_T[j] / self.A[j][j]
else:
self.x[j] = (self.b_T[j] - sum_ax(k=j)) / self.A[j][j]
def get_result(self):
return self.x
A = [[0.2641, 0.1735, 0.8642],
[0.9411, -0.0175, 0.1463],
[-0.8641, -0.4243, 0.0711]]
b_T = [-0.7521, 0.6310, 0.2501]
G = gauss(A=A, b_T=b_T)
G.xiao_yuan()
G.hui_dai()
y = G.get_result()
因为起始坐标原因,函数传参部分细节需要注意
标签:.__,return,Guass,python,self,AB,np,def,消去法 From: https://www.cnblogs.com/boran/p/16732057.html