數值計算·第十集:高斯-賽德爾迭代法(Numpy版)

ps:這是按照自己的理解寫的程序,代碼比較糙。獻醜了,望海涵!

#GaussSeidelIteration interation
import numpy as np
import sys

def GaussSeidel(x0,A,b):
    
    if A.shape[1] != x0.shape[0] and A.shape[0] != b.shape[0]:
        sys.exit('Please try again! Because the dimensions are not equal.')
    
    k = 0
    eps = 1e-6
    flag = True
    count = 1
    
    n = x0.shape[0]
    x = np.zeros([n,1])
    
    
    while flag:
        for i in range(0,n):
            x[i] = (b[i] - A[i,0:i]@x[0:i]-A[i,i+1:]@x0[i+1:])/A[i,i]
            
        print('No.{}:\nx = {}'.format(count,x))
        count += 1
        
        if np.linalg.norm(x-x0,np.inf)<eps:
            flag = False
            print('The optimal value: x = ',x.T)

        x0 = x.copy()
        

x0 = np.array([[0],[0],[0]])
A = np.array([[8,-3,2],[4,11,-1],[6,3,12]])
b = np.array([[20],[33],[36]])

#GaussSeidel(x0,A,b)

x1 = np.array([[0],[0],[0]])
A1 = np.array([[5,2,1],[-1,4,2],[2,-3,10]])
b1 = np.array([[-12],[20],[3]])

#GaussSeidel(x1,A1,b1)

x2 = np.array([[0],[0],[0]])
A2 = np.array([[10,-1,-2],[-1,10,-2],[-1,-1,5]])
b2 = np.array([[72],[83],[42]])

GaussSeidel(x2,A2,b2)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章