Search code examples
pythonnumpymatheigenvector

Numpy outputting incorrect eigenvectors


I need to output eigenvalues and eigenvectors of a matrix. This seems like a trivial task using a function like numpy.linalg.eig. It turned out that it outputs correct eigenvalues but there is something wrong with eigenvectors.

Say we have a matrix A:

We know that the eigenvalues for this are:

Similarly, the eigenvectors for this are:

So using the equation,

For the first eigenvalue, we have:

You can test it using this code:

import numpy as np

A = np.array([[0, 2],
              [2, 3]])
I = np.eye(2)

eigenvector = [[1, 2], 
               [-2, 1]]
eigenvalue = [4, -1]

for i in range(2):
    print(f"eigenvalue = {eigenvalue[i]}, eigenvector = {eigenvector[i]}")
    print(f"(A-λ*I)v = {(A-eigenvalue[i]*I)@eigenvector[i]}")
    print(" ")

However, if we try numpy.linalg.eig to compute the eigenvectors and eigenvalues we run into some issues.

This finds the following, incorrect, eigenvalues:

Similarly, the eigenvectors that it finds are:

Now when we test the first eigenvector we get results that are different than zero:

You can see this using this code:

import numpy as np
from numpy.linalg import eig

A = np.array([[0, 2],
              [2, 3]])
I = np.eye(2)

eigenvalue, eigenvector = eig(A)
for i in range(2):
    print(f"eigenvalue = {eigenvalue[i]}, eigenvector = {eigenvector[i]}")
    print(f"(A-λ*I)v = {(A-eigenvalue[i]*I)@eigenvector[i]}")
    print(" ")

What am I doing wrong? How can I get the correct eigenvectors using numpy.linalg.eig?


Solution

  • Numpy returns the normalized eigenvectors, i.e. they have unit length (as outlined in the documentation). Also, you need to select the first column to get the first eigenvector. If you use eigenvector[:, 0]*np.sqrt(5), you will see that the eigenvector is the same as the one you computed by hand.