矩阵特征值及特征向量计算
调包
import numpy as np
幂法
def M(A,u0,epsilon = 1e-6,M=100):
uk = u0
mk_1 = 1
k = 0
while True:
k += 1
vk = A*uk
mk = vk[np.argmax(np.abs(vk))]
uk = vk / mk
if np.abs(mk - mk_1) < epsilon:
return mk,uk,k
if k == M:
print("算法失败!")
return
mk_1 = mk
幂法加速
def M_plus(A,u0,epsilon,M=100,alpha = 0.5):
uk = u0
mk_1 = 1
k = 0
A = A - alpha * np.eye(len(A))
while True:
k += 1
vk = A*uk
mk = vk[np.argmax(np.abs(vk))]
uk = vk / mk
if np.abs(mk - mk_1) < epsilon:
return mk,uk,k
if k == M:
print("算法失败!")
return
mk_1 = mk
反幂法
def M_anti(A,u0,epsilon = 1e-6,M=100):
uk = u0
mk_1 = 1
k = 0
while True:
k += 1
vk = np.matrix(np.linalg.inv(A.A))*uk
mk = vk[np.argmax(np.abs(vk))]
uk = vk / mk
if np.abs(mk - mk_1) < epsilon:
return (1/mk).A,uk.A,k
if k == M:
print("算法失败!")
return
mk_1 = mk
|