Search code examples
pythonnumpyscipyeigenvalueeigenvector

Incorrect eigenvalue with simply QR iteration by python


I try to solve eigenvalue and eigenvector by QR iteration, the code is super simple. But the answer by QR iteration always has some opposite or incorrect values compare to the answer by linalg.eigs.

import numpy as np
import scipy.linalg as linalg

def qr_iteration(A):
   for i in range(100):
      Q, R = linalg.qr(A)
      A = np.dot(R, Q)
   return np.diag(R), Q

a, b = linalg.eig(A)
c, d = qr_iteration(A)
print(a)   # [ 1.61168440e+01+0.j -1.11684397e+00+0.j -1.30367773e-15+0.j]
print(c)   # [-1.61168440e+01  1.11684397e+00 -1.33381856e-15]

Some of the values are opposite to the correct answer Which part of my code is wrong? Thanks for all the answers.


Solution

  • The final eigenvalues should be found as the diagonal elements of A instead of R (change the return statement to np.diag(A)). Moreover, the order of the eigenvalues appearing in the diagonal may differ from other algorithms.

    Are you dealing with real symmetric matrices? If not, the eigenvalues may be complex and QR algorithm should not be applied. If it has complex eigenvalues, those eigenvalues come in pairs having the same magnitude and the algorithm will not converge. You will never get imaginary numbers using your procedure.

    To get the eigenvectors, you need to multiply all the Q's, i.e. $Q1 Q2 Q3...$; the column vectors are the corresponding eigenvectors (don't know how to type latex here)