Ray
Ray

Reputation: 8573

Python numpy compute first eigenvalue and eigenvector

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 2x2. 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 2x2 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!

Upvotes: 9

Views: 27428

Answers (3)

Raymond Hettinger
Raymond Hettinger

Reputation: 226316

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 2x2 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 3x3 and larger.

Upvotes: 1

Josh Berryman
Josh Berryman

Reputation: 21

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)

Upvotes: 2

Related Questions