高斯赛德尔迭代非常常用,看到网上很多例子写的不够简洁,这里我写了一个,供参考
import numpy as np
def gauss_seidel(A,b,x1,eps=1.e-6):
n = len(A)
max_iter = 200
iters = 0
while abs(np.dot(A[0,:],x1) - b)[0] > eps and iters < max_iter:#对二维矩阵,只判断了一行
#判断,为了减少计算量,只判断第一个点和最后一个点
for i in range(n):
median_value1 = 0.
for j in range(0,n):
if j != i: #只需要挖掉i==j的点就可以了
median_value1 = median_value1+A[i,j]*x1[j]
x1[i] = (b[i] - median_value1 )/A[i,i]
iters += 1
return x1,iters
A = np.array([
[10.,-1.,-2],
[-1.,10.,-2.],
[-1.,-1.,5. ]
])
b = [72.,83.,42.]
initial = np.array([1.,1.,1.])
x1,iters = gauss_seidel(A,b,initial)
print("iters = ",iters)
print("solution = ",x1)
print(np.dot(A,x1))