Python中求解线性方程组的Gauss-Seidel方法

2024-06-10 20:57:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用python中的Gauss-seidel方法求解一个线性代数方程,但在这里似乎找不到错误。下面的图片中附有我试图与代码一起编写的等式。 多谢各位

高斯-赛德尔方程:
Gauss-seidel Equation

代码:

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)

Tags: 代码infornprangeabsarraytemp