ps:這是按照自己的理解寫的程序,代碼比較糙。獻醜了,望海涵!
#Jacobi interation
import numpy as np
import sys
def Jacobi(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.empty([n,1])
while flag:
for i in range(0,n):
x[i] = (b[i] - A[i,:]@x0 + A[i,i]*x0[i])/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]])
#Jacobi(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]])
#Jacobi(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]])
Jacobi(x2,A2,b2)
'''
運行結果:
No.1:
x = [[7.2]
[8.3]
[8.4]]
No.2:
x = [[ 9.71]
[10.7 ]
[11.5 ]]
No.3:
x = [[10.57 ]
[11.571]
[12.482]]
No.4:
x = [[10.8535]
[11.8534]
[12.8282]]
No.5:
x = [[10.95098]
[11.95099]
[12.94138]]
No.6:
x = [[10.983375]
[11.983374]
[12.980394]]
No.7:
x = [[10.9944162]
[11.9944163]
[12.9933498]]
No.8:
x = [[10.99811159]
[11.99811158]
[12.9977665 ]]
No.9:
x = [[10.99936446]
[11.99936446]
[12.99924463]]
No.10:
x = [[10.99978537]
[11.99978537]
[12.99974578]]
No.11:
x = [[10.99992769]
[11.99992769]
[12.99991415]]
No.12:
x = [[10.9999756 ]
[11.9999756 ]
[12.99997108]]
No.13:
x = [[10.99999178]
[11.99999178]
[12.99999024]]
No.14:
x = [[10.99999723]
[11.99999723]
[12.99999671]]
No.15:
x = [[10.99999906]
[11.99999906]
[12.99999889]]
No.16:
x = [[10.99999968]
[11.99999968]
[12.99999963]]
The optimal value: x = [[10.99999968 11.99999968 12.99999963]]
'''