求矩阵全部特征值和特征向量的QR方法
程序员文章站
2022-07-15 10:46:49
...
import numpy as np
import math
def sgn1(x):
if x > 0:
return 1
elif x == 0:
return 0
elif x < 0:
return -1
ai2 = np.mat([[-1, 2, 1],
[2, -4, 1],
[1, 1, -6]], dtype=float)
n = ai2.shape[0]
for i in range(n-2):
c = -1*sgn1(ai2[i+1, i])*np.sqrt(np.sum(np.multiply(ai2[i+1:n, i], ai2[i+1:n, i])))
lou = np.sqrt(2*c*(c-ai2[i+1, i]))
l = ai2[i+1:n, i]
l1 =l.copy()
l1[0] = l1[0]-c
b = l1/lou
a = np.mat(np.zeros((i+1, 1)))
u = np.vstack((a, b))
I = np.mat(np.eye(n))
H = I-2*u*u.T
ai2 = H*ai2*H.T
err = 1
ai3 = ai2.copy()
for t in range(88):
i = 0
sita = math.atan(ai2[i+1, i]/ai2[i, i])
c = math.cos(sita)
s = math.sin(sita)
V1 = np.mat(np.eye(n))
V1[i,i] = c
V1[i+1,i] = -s
V1[i,i+1] = s
V1[i+1, i+1] = c
ai2 = V1*ai2
i = 1
sita = math.atan(ai2[i+1, i]/ai2[i, i])
c = math.cos(sita)
s = math.sin(sita)
V2 = np.mat(np.eye(n))
V2[i,i] = c
V2[i+1,i] = -s
V2[i,i+1] = s
V2[i+1, i+1] = c
ai2 = V2*ai2
ai2 = ai2*V1.T*V2.T
print('迭代88次后得:')
print(ai2)
print('矩阵的特征值为{:.7},{:.7},{:.7}'.format(ai2[0, 0],ai2[1, 1],ai2[2, 2]))