-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathncao2.py
More file actions
87 lines (80 loc) · 2.28 KB
/
ncao2.py
File metadata and controls
87 lines (80 loc) · 2.28 KB
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
75
76
77
78
79
80
81
82
83
84
85
86
87
# -*- coding: utf-8 -*-
"""
numerical computation and optimization-homework2
@author: 10152510119 徐紫琦
"""
import numpy as np
#generate the three matrix used in different iterative methods
def generateLUD(A):
D=np.mat(np.diag(np.diag(A)))
L=np.mat((-1)*np.tril(A,k=-1))
U=np.mat((-1)*np.triu(A,k=1))
return D,L,U
#implementation of jacobi iterative method
def jacobi(A,b):
X=np.zeros((100,1))
X0=X
D,L,U=generateLUD(A)
#B=(D)^(-1)*(L+U)
B=np.linalg.inv(np.mat(D))*np.mat(L+U)
#f=(D)^(-1)*(b)
f=np.linalg.inv(np.mat(D))*np.mat(b)
#X=B*X+f <-keep iterating until X converges to the final result
while True:
X=np.dot(B,X0)+f
if np.linalg.norm(np.dot(A,X)-b)/np.linalg.norm(b)<0.000001:
break
X0 = X
return X
#implementation of Gauss-Seidel iterative method
def gaussian(A,b):
X=np.zeros((100,1))
X0=X
D,L,U=generateLUD(A)
#B=(D-L)^(-1)*(U)
B=np.linalg.inv(np.mat(D-L))* np.mat(U)
#f=(D-L)^(-1)*(b)
f=np.linalg.inv(np.mat(D-L))*np.mat(b)
#X=B*X+f <-keep iterating until X converges to the final result
while True:
X=np.dot(B,X0)+f
if np.linalg.norm(np.dot(A,X)-b)/np.linalg.norm(b)<0.000001:
break
X0=X
return X
#implementation of successive overrelaxation method
def SOR(A,b):
D,L,U=generateLUD(A)
w=1.05
X=np.mat(np.zeros((100,1)))
X0=X
#B=(D-wL)^(-1)*[(1-w)D+wU
B=np.dot(np.linalg.inv(D-w*L),(1-w)*D+w*U)
#f=w(D-wL)^(-1)*b
f=np.dot(w*np.linalg.inv(D-w*L),b)
#X=B*X+f <-keep iterating until X converges to the final result
while True:
X=np.dot(B,X0)+f
if np.linalg.norm(A*X0-b)/np.linalg.norm(b)<0.000001:
break
X0=X
return X
def main():
A=np.mat(np.zeros((100,100)))
for i in range(0,100):
if i>0:
A[(i,i-1)]=-1
if i<99:
A[(i,i+1)]=-1
A[(i,i)]=2
b=np.mat(np.ones((100,1)))
print("Standard result got from np.linalg.solve:")
print(np.linalg.solve(A,b))
print("Result of Jacobi Iterative Method:")
print(jacobi(A,b))
print("Result of Gauss-Seidel Iterative Method:")
print(gaussian(A,b))
print("Result of SOR Method:")
print(SOR(A,b))
if __name__=='__main__':
main()