8
votes

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!

3
Umm, what do you mean by "long time"? %timeit np.linalg.eig(np.random.rand(2,2)) gives 10000 loops, best of 3: 208 us per loop. That's reasonably fast, I must say.Avaris
For 2x2 Matrix numpy is slow due the overhead, just use: math.harvard.edu/archive/21b_fall_04/exhibits/2dmatrices/…tillsten
@Avaris, don't include a call to a random-number generator in your timing tests!Ahmed Fasih

3 Answers

2
votes

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)
1
votes

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: http://www.scipy.org/NumPy_for_Matlab_Users

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.