学习数值分析这门课程时,对高斯消元法及主元素法部分代码的编写,希望能帮到大家,也希望能有大神对我做的不到位的地方进行指正。直接上代码。
def guess(A,B): #A-系数矩阵,B-对应方程的矩阵
n = len(A)
if n != len(A[0]): #确定系数矩阵符合未知数等于方程数
return False
for k in range(n-1):
# for l in range(k,n):
# if abs(A[l][k]) > abs(A[k][k]):
# A[k],A[l] = A[l],A[k]
# B[k],B[l] = B[l],B[k]
# 主元素法加上这几行进行排序操作
if A[k][k] == 0: #确定Akk不为零
return False
else:
for i in range(k+1,n):
p = A[i][k]/A[k][k] #记比值为p
B[i] -= p * B[k]
for j in range(k,n):
A[i][j] -= p * A[k][j]
print(A) #打印每一次消元后的系数矩阵,方便查看问题
X = [0]*n #记解矩阵为X
X[n-1] = B[n-1]/A[n-1][n-1] #回带过程
for i in range(n-2,-1,-1):
c = B[i]
for j in range(i+1,n):
c -= A[i][j]*X[j]
X[i] = c/A[i][i]
return X #返回解
之后利用例题对比一下主元素法和guess消去法的运行结果
X = [[0.5,1.1,3.1],
[2.0,4.5,0.36],
[5.0,0.96,6.5]]
Y = [6.0,0.020,0.96]
print(guess(X,Y))
guess消去法:
[[0.5, 1.1, 3.1], [0.0, 0.09999999999999964, -12.040000000000001], [0.0, -10.04, -24.5]] [[0.5, 1.1, 3.1], [0.0, 0.09999999999999964, -12.040000000000001], [0.0, 0.0, -1233.3160000000044]] [-2.599999999999879, 0.9999999999999467, 1.9999999999999996]
主元素法:
[[5.0, 0.96, 6.5], [0.0, 1.004, 2.45], [0.0, 4.116, -2.24]] [0.96, 5.904, -0.364] [[5.0, 0.96, 6.5], [0.0, 4.116, -2.24], [0.0, 0.0, 2.9963945578231295]] [0.96, -0.364, 5.992789115646258] [-2.5999999999999996, 1.0, 1.9999999999999998]