-
Notifications
You must be signed in to change notification settings - Fork 0
/
4-1.py
74 lines (66 loc) · 1.77 KB
/
4-1.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# @Time : 2022/05/18 15:52:41
# @Author : dch0319
# @File : 4-1.py
# @Software: Visual Studio Code
import numpy as np
def Jacobi(A, b):
A = np.array(A, dtype=np.float64)
dim = A.shape[0]
b = np.array(b, dtype=np.float64)
D = np.diag(np.diagonal(A))
L = np.tril(A, -1)
U = np.triu(A, 1)
x = np.zeros((dim, 1))
x_list = [x]
while True:
x = np.linalg.inv(D) @ (b - (L + U) @ x)
x_list.append(x)
if (x_list[-1] - x_list[-2]).max() < 0.5 * 10**(-6):
break
print("Jacobi迭代: ")
print(x_list[-1])
return x_list[-1]
def GS(A, b):
A = np.array(A, dtype=np.float64)
dim = A.shape[0]
b = np.array(b, dtype=np.float64)
D = np.diag(np.diagonal(A))
L = np.tril(A, -1)
U = np.triu(A, 1)
x = np.zeros((dim, 1))
x_list = [x]
while True:
x = np.linalg.inv(D + L) @ (b - U @ x)
x_list.append(x)
if (x_list[-1] - x_list[-2]).max() < 0.5 * 10**(-6):
break
print("GS迭代: ")
print(x_list[-1])
return x_list[-1]
def SOR(A, b):
omega = 1.1
A = np.array(A, dtype=np.float64)
dim = A.shape[0]
b = np.array(b, dtype=np.float64)
D = np.diag(np.diagonal(A))
L = np.tril(A, -1)
U = np.triu(A, 1)
x = np.zeros((dim, 1))
x_list = [x]
while True:
x = np.linalg.inv(D + omega * L) @ (
(1 - omega) * D @ x -
omega * U @ x) + omega * np.linalg.inv(D + omega * L) @ b
x_list.append(x)
if (x_list[-1] - x_list[-2]).max() < 0.5 * 10**(-6):
break
print("SOR迭代: ")
print(x_list[-1])
return x_list[-1]
A = [[3, -1, 1], [1, -8, -2], [1, 1, 5]]
b = [[-2], [1], [4]]
Jacobi(A, b)
GS(A, b)
SOR(A, b)