数值分析实验之线性方程组的迭代求解(Python实现)

详细实验指导见上一篇,此处只写内容啦

  实验内容: 求解如下4元线性方程组的近似解。

       数值分析实验之线性方程组的迭代求解(Python实现)

Jacobi迭代过程

import numpy as np

A = np.array([[10,-1,2,0],[-1,11,-1,3],[2,-1,10,-1],[0,3,-1,8]])
B = np.array([6, 25, -11, 15])
x0 = np.array([0.0, 0, 0, 0])
x = np.array([0.0, 0, 0, 0])

times = 0

while True:
    for i in range(4):
        temp = 0
        for j in range(4):
            if i != j:
                temp += x0[j] * A[i][j]
        x[i] = (B[i] - temp) / A[i][i]
    calTemp = max(abs(x - x0))
    times += 1
    if calTemp < 1e-5:
        break
    else:
        x0 = x.copy()

print(times)
print(x)

    运行结果:

    数值分析实验之线性方程组的迭代求解(Python实现)

Gauss-Seidel迭代

import numpy as np

A = np.array([[10,-1,2,0],[-1,11,-1,3],[2,-1,10,-1],[0,3,-1,8]])
B = np.array([6, 25, -11, 15])
x0 = np.array([0.0, 0, 0, 0])
x = np.array([1.0, 2, -1, 1])
times = 0

while True:
    for i in range(4):
        temp = 0
        tempx = x0.copy()
        for j in range(4):
            if i != j:
                temp += x0[j] * A[i][j]
        x[i] = (B[i] - temp) / A[i][i]
        x0[i] = x[i].copy()
    calTemp = max(abs(x - tempx))
    times += 1
    if calTemp < 1e-5:
        break
    else:
        x0 = x.copy()

print(times)
print(x)

    运行结果:

    数值分析实验之线性方程组的迭代求解(Python实现)

SOR迭代法

import numpy as np

A = np.array([[10,-1,2,0],[-1,11,-1,3],[2,-1,10,-1],[0,3,-1,8]])
B = np.array([6, 25, -11, 15])
x0 = np.array([0.0, 0, 0, 0])
x = np.array([1.0, 2, -1, 1])
w = 1.2
times, MT = 0, 1000

while times < MT:
    tempx = x0.copy()
    for i in range(4):
        temp = 0
        for j in range(4):
            if i != j:
                temp += x0[j] * A[i][j]
        x[i] = (B[i] - temp) / A[i][i]
        x0[i] = x[i]
    x = w * x + (1-w) * tempx
    calTemp = max(abs(x - tempx))
    times += 1
    if calTemp < 1e-5:
        break
print(times)
print(x)

    运行结果:

    数值分析实验之线性方程组的迭代求解(Python实现)