Python解線性方程組的迭代法(3)————逐次超鬆弛(SOR)迭代法

ThinkZtoA發表於2020-10-31

程式碼

import numpy as np


def sor(A, b, N, w):
    x = np.mat(np.zeros((A.shape[0], 1)))
    k = 0
    n = A.shape[0]
    xj = x.copy()
    while k <= N:
        for i in range(n):
            for j in range(n):
                x[i, 0] = (1 - w) * x[i, 0] + w * (b[i, 0] - A[i, 0:i]*x[0:i, 0] - A[i, i+1:n] * xj[i+1:n, 0])/A[i, i]
        if sum(abs(A*x - b)) < 10*-8:
            break
        k = k + 1
        xj = x.copy()
    if k == N:
        print('超過最大迭代次數')
    return x


if __name__ == "__main__":
    w = float(input('請輸入鬆弛因子:'))
    A = np.mat([[10, -1, -2],
              [-1, 10, -2],
              [-1, -1, 5]])
    b = np.mat([[72], [83], [42]])
    print('求解結果:')
    print(sor(A, b, 1000, w))

求解結果如下:

在這裡插入圖片描述

相關文章