Jacobi迭代法
迭代公式
代码
import numpy as np
def Jacobi(A,b,n=1000,eps=1e-6):
if len(A) == len(b):
x = []
for i in range(len(A)):
x.append(0)
count = 0
while count < n:
nx = []
for i in range(len(x)):
nxi = b[i]
for j in range(len(A[i])):
if j!=i:
nxi -= A[i][j]*x[j]
nxi = nxi/A[i][i]
nx.append(nxi)
if np.linalg.norm(np.mat(nx)-np.mat(x)) < eps:
return nx
x = nx
count = count + 1
return False
else:
return False
A = [[8,-3,2],[4,11,-1],[6,3,12]]
b = [20,33,36]
print(Jacobi(A,b,1000,1e-10))
Gauss-Seidel迭代法
迭代公式
代码
import numpy as np
def Gauss_Seidel(A,b,n=1000,eps=1e-6):
if len(A) == len(b):
x = []
for i in range(len(A)):
x.append(0)
count = 0
while count < n:
nx = []
for i in range(len(x)):
nxi = b[i]
for j in range(len(A[i])):
if j < i:
nxi -= A[i][j]*nx[j]
if j > i:
nxi -= A[i][j]*x[j]
nxi = nxi/A[i][i]
nx.append(nxi)
if np.linalg.norm(np.mat(nx)-np.mat(x)) < eps:
print(count)
return nx
x = nx
count = count + 1
return False
else:
return False
A = [[8,-3,2],[4,11,-1],[6,3,12]]
b = [20,33,36]
print(Gauss_Seidel(A,b,1000,1e-10))
SOR
迭代公式
其中.
代码
import numpy as np
def SOR(A,b,w=0.5,n=1000,eps=1e-6):
if len(A) == len(b):
x = []
for i in range(len(A)):
x.append(0)
count = 0
while count < n:
nx = []
for i in range(len(x)):
nxi = b[i]
for j in range(len(A[i])):
if j < i:
nxi -= A[i][j]*nx[j]
if j > i:
nxi -= A[i][j]*x[j]
nxi = w*nxi/A[i][i]
nxi += (1-w)*x[i]
nx.append(nxi)
if np.linalg.norm(np.mat(nx)-np.mat(x)) < eps:
print(count)
return nx
x = nx
count = count + 1
return False
else:
return False
A = [[8,-3,2],[4,11,-1],[6,3,12]]
b = [20,33,36]
print(SOR(A,b,0.5,1000,1e-10))
网友评论