高斯赛德尔法求解 Python 中的线性方程组
Gauss Seidel Method to solve Linear equations in Python
我正在尝试在 python 中使用高斯-塞德尔方法求解线性代数方程,但似乎无法在此处找到错误。我试图连同我的代码一起编写的方程式附在下图中。
谢谢。
高斯赛德尔方程:
代码:
import numpy as np
A= np.array([4.,-1.,1.,-1.,4.,-2.,1.,-2.,4.]).reshape(3,3)
B= np.array([12.,-1.,5.]).reshape(3,1)
N= len(B)
print (N)
x=np.zeros(N)
xold= np.array([10.,10.,10.]).reshape(3,1)
tol=0.01
x=np.array([5.,5.,5.]).reshape(3,1)
#for i in range (N):
# print ("start at i=",i, "and xi=",x[i])
temp=0
while (abs(x[0]-xold[0])>tol):
xold=x
print ("absstart=",abs(x-xold))####
for i in range (N):
for j in range (N):
if j!= i:
temp+=A[i,j]*x[j]
#print ("temp=",temp)####
x[i]=(1/A[i,i])*(B[i]-temp)
#print ("end at x",i,"=",x[i])####
#print ("abs= ",abs(x-xold))####
print (x)
print (xold)
可能是因为这行代码
temp = 0
位置不对。
不是应该在 i 的每次迭代中将其重置为零吗?
我正在尝试在 python 中使用高斯-塞德尔方法求解线性代数方程,但似乎无法在此处找到错误。我试图连同我的代码一起编写的方程式附在下图中。 谢谢。
高斯赛德尔方程:
代码:
import numpy as np
A= np.array([4.,-1.,1.,-1.,4.,-2.,1.,-2.,4.]).reshape(3,3)
B= np.array([12.,-1.,5.]).reshape(3,1)
N= len(B)
print (N)
x=np.zeros(N)
xold= np.array([10.,10.,10.]).reshape(3,1)
tol=0.01
x=np.array([5.,5.,5.]).reshape(3,1)
#for i in range (N):
# print ("start at i=",i, "and xi=",x[i])
temp=0
while (abs(x[0]-xold[0])>tol):
xold=x
print ("absstart=",abs(x-xold))####
for i in range (N):
for j in range (N):
if j!= i:
temp+=A[i,j]*x[j]
#print ("temp=",temp)####
x[i]=(1/A[i,i])*(B[i]-temp)
#print ("end at x",i,"=",x[i])####
#print ("abs= ",abs(x-xold))####
print (x)
print (xold)
可能是因为这行代码
temp = 0
位置不对。
不是应该在 i 的每次迭代中将其重置为零吗?