【问题标题】:Gauss Seidel Method to solve Linear equations in Python高斯赛德尔方法在 Python 中求解线性方程组
【发布时间】:2020-12-27 22:54:55
【问题描述】:

我正在尝试在 python 中使用 Gauss-seidel 方法求解线性代数方程,但似乎在这里找不到错误。我试图与我的代码一起编写的方程式附在下图中。 谢谢。

高斯-赛德尔方程:

代码:

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)

【问题讨论】:

  • Gauss-Seidel 的维基百科页面提供了 Python 实现。你有对比过你的代码吗?

标签: python python-3.x linear-algebra


【解决方案1】:

可能是因为这行代码

temp = 0

不是在正确的地方。

不是应该在 i 的每次迭代中重置为零吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    • 2014-01-17
    • 2022-01-16
    • 1970-01-01
    • 2017-07-27
    相关资源
    最近更新 更多