1
2
|
import numpy as np import time |
1.1 Gauss-Seidel迭代算法
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
|
def GaussSeidel_tensor_V2(A,b,Delta,m,n,M): start = time.perf_counter() find = 0 X = np.ones(n) d = np.ones(n) m1 = m - 1 m2 = 2 - m for i in range (M): print ( 'X' ,X) x = np.copy(X) #迭代更新 for j in range (n): a = np.copy(A) for k in range (m - 2 ): a = np.dot(a,x) for k in range (n): d[k] = a[k,k] a[k,k] = m2 * a[k,k] x[j] = (b[j] - np.dot(a[j],x)) / (m1 * d[j]) #判断是否满足精度要求 if np. max (np.fabs(X - x))<Delta: find = 1 break X = np.copy(x) end = time.perf_counter() print ( '时间:' ,end - start) print ( '迭代' ,i) return X,find,i,end - start |
1.2张量A的生成函数和向量b的生成函数:
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
|
def Creat_A(m,n): #生成张量A size = np.full(m, n) X = np.ones(n) while 1 : #随机生成给定形状的张量A A = np.random.randint( - 49 , 50 ,size = size) #判断Dx**(m-2)是否非奇异,如果是,则满足要求,跳出循环 D = np.copy(A) for i1 in range (n): for i2 in range (n): if i1! = i2: D[i1,i2] = 0 for i in range (m - 2 ): D = np.dot(D,X) det = np.linalg.det(D) if det! = 0 : break #将A的对角面张量扩大十倍,使对角面占优 for i1 in range (n): for i2 in range (n): if i1 = = i2: A[i1,i2] = A[i1,i2] * 10 print ( 'A:' ) print (A) return A #由A和给定的X根据Ax**(m-1)=b生成向量b def Creat_b(A,X,m): a = np.copy(A) for i in range (m - 1 ): a = np.dot(a,X) print ( 'b:' ) print (a) return a |
1.3 对称张量S的生成函数:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
def Creat_S(m,n): #生成对称张量B size = np.full(m, n) S = np.zeros(size) print ( 'S' ,S) for i in range ( 4 ): #生成n为向量a a = np.random.random(n) * np.random.randint( - 5 , 6 ) b = np.copy(a) #对a进行m-1次外积,得到秩1对称张量b for j in range (m - 1 ): b = outer(b,a) #将不同的b叠加得到低秩对称张量S S = S + b print ( 'S:' ) print (S) return S def outer(a,b): c = [] for i in b: c.append(i * a) return np.array(c) return a |
1.4 实验二
1
2
3
4
5
6
7
8
9
|
def test_2(): Delta = 0.01 #精度 m = 3 #A的阶数 n = 3 #A的维数 M = 200 #最大迭代步数 X_real = np.array( [ 2 , 3 , 4 ]) A = Creat_A(m,n) b = Creat_b(A,X_real,m) GaussSeidel_tensor_V2(A,b,Delta,m,n) |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://www.cnblogs.com/Fengqiao/p/Gauss-Seidel-tensor.html