How do you compute eigenvalues and eigenvectors using Sage?
Sage has a full range of functions for computing eigenvalues and both
left and right eigenvectors and eigenspaces. If our matrix is
, then
eigenmatrix_right (eigenmatrix_left) command also
gives matrices
and
such that
(
).
sage: A = matrix(QQ, [[1,1,0],[0,2,0],[0,0,3]]) sage: A [1 1 0] [0 2 0] [0 0 3] sage: A.eigenvalues() [3, 2, 1] sage: A.eigenvectors_right() [(3, [ (0, 0, 1) ], 1), (2, [ (1, 1, 0) ], 1), (1, [ (1, 0, 0) ], 1)] sage: A.eigenspaces_right() [ (3, Vector space of degree 3 and dimension 1 over Rational Field User basis matrix: [0 0 1]), (2, Vector space of degree 3 and dimension 1 over Rational Field User basis matrix: [1 1 0]), (1, Vector space of degree 3 and dimension 1 over Rational Field User basis matrix: [1 0 0]) ] sage: D, P = A.eigenmatrix_right() sage: D [3 0 0] [0 2 0] [0 0 1] sage: P [0 1 1] [0 1 0] [1 0 0] sage: A*P == P*D True
A word of caution - if the eigenvalues are not in the fraction field
of the base ring of the matrix space (the eigenvalues below are
) then the output of eigenspaces_right and
eigenspaces_left only lists a single eigenspace for each
irreducible factor of the characteristic polynomial.
Also, currently Sage does not implement multiprecision numerical
eigenvalues/eigenvectors, so calling the eigen functions on a matrix
from CC or RR will probably give inaccurate and
nonsensical results (a warning is also printed). Matrices over
CDF and RDF should work, though.
sage: MS = MatrixSpace(QQ, 2, 2) sage: A = MS([1,-4,1, -1]) sage: A.eigenspaces_left() [ (a0, Vector space of degree 2 and dimension 1 over Number Field in a0 with defining polynomial x^2 + 3 User basis matrix: [ 1 a0 - 1]) ] sage: MS = MatrixSpace(CC, 2, 2) sage: A = MS([1,-4,1, -1]) sage: A.eigenspaces() # random output [ (1.73205080756888*I, [ ]), (-1.73205080756888*I, [ ]) ]
Another approach is to use the interface with Maxima:
sage: A = maxima("matrix ([1, -4], [1, -1])")
sage: eig = A.eigenvectors()
sage: eig
[[[-sqrt(3)*%i,sqrt(3)*%i],[1,1]],[1,(sqrt(3)*%i+1)/4],[1,-(sqrt(3)*%i-1)/4]]
Here are two more examples:
sage: A = maxima("matrix ([11, 0, 0], [1, 11, 0], [1, 3, 2])")
sage: A.eigenvectors()
[[[2,11],[1,2]],[0,0,1],[0,1,1/3]]
sage: A = maxima("matrix ([-1, 0, 0], [1, -1, 0], [1, 3, 2])")
sage: A.eigenvectors()
[[[-1,2],[2,1]],[0,1,-1],[0,0,1]]
Finally, you can use Sage's GAP interface as well to compute ``rational'' eigenvalues and eigenvectors:
sage: print gap.eval("A := [[1,2,3],[4,5,6],[7,8,9]]")
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
sage: print gap.eval("v := Eigenvectors( Rationals,A)")
[ [ 1, -2, 1 ] ]
sage: print gap.eval("lambda := Eigenvalues( Rationals,A)")
[ 0 ]
See About this document... for information on suggesting changes.