简体   繁体   中英

How to find the eigenvalues and eigenvectors of a matrix with SymPy?

I want to calculate the eigenvectors x from a system A by using this: A x = λ x

The problem is that I don't know how to solve the eigenvalues by using SymPy. Here is my code. I want to get some values for x1 and x2 from matrix A

from sympy import *
x1, x2, Lambda = symbols('x1 x2 Lambda')
I = eye(2)
A = Matrix([[0, 2], [1, -3]])
equation = Eq(det(Lambda*I-A), 0)
D = solve(equation)
print([N(element, 4) for element in D]) # Eigenvalus in decimal form
print(pretty(D)) # Eigenvalues in exact form

X = Matrix([[x1], [x2]]) # Eigenvectors
T = A*X - D[0]*X # The Ax = %Lambda X with the first %Lambda = D[0]
print(pretty(solve(T, x1, x2)))

The methods eigenvals and eigenvects is what one would normally use here.

A.eigenvals() returns {-sqrt(17)/2 - 3/2: 1, -3/2 + sqrt(17)/2: 1} which is a dictionary of eigenvalues and their multiplicities. If you don't care about multiplicities, use list(A.eigenvals().keys()) to get a plain list of eigenvalues.

The output of eigenvects is a bit more complicated, and consists of triples (eigenvalue, multiplicity of this eigenvalue, basis of the eigenspace). Note that the multiplicity is algebraic multiplicity , while the number of eigenvectors returned is the geometric multiplicity , which may be smaller. The eigenvectors are returned as 1-column matrices for some reason...

For your matrix, A.eigenvects() returns the eigenvector [-2/(-sqrt(17)/2 + 3/2), 1] for the eigenvalue -3/2 + sqrt(17)/2 , and eigenvector [-2/(3/2 + sqrt(17)/2), 1] for eigenvalue -sqrt(17)/2 - 3/2 .

If you want the eigenvectors presented as plain lists of coordinates, the following

[list(tup[2][0]) for tup in A.eigenvects()]

would output [[-2/(-sqrt(17)/2 + 3/2), 1], [-2/(3/2 + sqrt(17)/2), 1]] . (Note this just picks one eigenvector for each eigenvalue, which is not always what you want)

sympy has a very convenient way of getting eigenvalues and eigenvectors: sympy-doc

Your example would simply become:

from sympy import *
A = Matrix([[0, 2], [1, -3]])
print(A.eigenvals())  #returns eigenvalues and their algebraic multiplicity
print(A.eigenvects())  #returns eigenvalues, eigenvects

This answer will help you when you all eignvectors, the solution above doesnt always give you all eienvectos for example this matrix A used below

# the matrix
A = Matrix([
    [4, 0, 1],
    [2, 3, 2],
    [1, 0, 4]
])

    sym_eignvects = []
    for tup in sMatrix.eigenvects():
        for v in tup[2]:
            sym_eignvects.append(list(v))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM