Python numpy compute first eigenvalue and eigenvector

Question:

I was wondering if there is a Python package, numpy or otherwise, that has a function that computes the first eigenvalue and eigenvector of a small matrix, say 2×2. I could use the linalg package in numpy as follows.

import numpy as np

def whatever():
    A = np.asmatrix(np.rand(2, 2))
    evals, evecs = np.linalg.eig(A)
    #Assume that the eigenvalues are ordered from large to small and that the
    #eigenvectors are ordered accordingly.
    return evals[0], evecs[:, 0]

But this takes a really long time. I suspect that it’s because numpy computes eigenvectors through some sort of iterative process. So I was wondering if there were a much faster algorithm that only returns the first (largest) eigenvalue and eigenvector, since I only need the first.

For 2×2 matrices of course I can write a function myself, that computes the eigenvalue and eigenvector analytically, but then there are problems with floating point computations, for example when I divide a very big number by a very small number, I get infinity or NaN. Does anyone know anything about this? Please help! Thank you in advance!

Asked By: Ray

||

Answers:

There doesn’t appear to be a numpy equivalent of Matlab’s eigs(A,B,k) for finding the k largest eigenvectors.

If you’re interested, Enthought has compiled a table showing the differences between Matlab and numpy. That should be helpful for answering questions like this one: Link

One other thought, for 2×2 matrices, I don’t think eigs(A,B,1) would help anyway. The effort involved in computing the first eigenpair leaving the matrix transformed to where the second emerges directly. There is only benefit for 3×3 and larger.

Answered By: Raymond Hettinger

According to the docs:

http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.eig.html

and also to my own experience, numpy.linalg.eig(A) does NOT sort the eigenvectors in any particular order, which is what the OP and subsequent seem to be assuming. I suggest something like:

rearrangedEvalsVecs = sorted(zip(evals,evecs.T),
                                    key=lambda x: x[0].real, reverse=True)
Answered By: Josh Berryman
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.