如何在jacob算法中实现矩阵乘法?

时间:2019-06-15 18:47:50

标签: python-3.x

我想实现jacobian算法来查找矩阵的特征值。我的问题是A矩阵,当我将其乘以E及其转置后,它不会改变。(jacobian算法仅适用于对称矩阵)

import numpy as np

def find_max_index(arr):
    maximum = 0
    index = [None, None]
    for i in range(len(arr)):
        for j in range(len(arr)):
            if abs(arr[i][j]) > maximum and i != j:
                maximum = arr[i][j]
                index = [i, j]
    return index

A = np.array([[1, 0, -5], [0, 2, 6], [-5, 6, 3]], dtype=float)
size = len(A)

print(np.linalg.eig(A))

e = 0.0001

max_index = find_max_index(A)


if np.max(np.abs(A - np.diag(np.diag(A)))) < e:
    print(np.diag(A))

finished = False

i = 0

while not finished:
    r = -A[max_index[0]][max_index[1]]
    s = (A[max_index[0]][max_index[0]] - A[max_index[1]][max_index[1]])/2
    t = np.around(np.sqrt(np.around(np.power(r, 2), 4) + np.around(np.power(s, 2), 4)), 4)

    cos_theta = np.around(np.sqrt((np.around(t + abs(s), 4))/np.around(2*t, 4)), 4)

    sin_theta = np.around(abs(r) / (np.around(2*t*cos_theta, 4)), 4)


    E = np.identity(size)
    E[max_index[0]][max_index[0]] = cos_theta
    E[max_index[0]][max_index[1]] = sin_theta
    E[max_index[1]][max_index[0]] = -sin_theta
    E[max_index[1]][max_index[1]] = cos_theta

    A = np.around(np.dot(np.transpose(E), np.around(np.dot(A, E), 4)),4) 
    print(A)
    if np.max(np.abs(A - np.diag(np.diag(A)))) < e:
        print(np.diag(A))
        finished = True

0 个答案:

没有答案