如何使用 SymPy 查找矩阵的特征值和特征向量?

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

我想计算系统 A​​ 的特征向量 x,方法是:A​​ x = λ x

问题是我不知道如何使用 SymPy 求解特征值。 这是我的代码。我想从矩阵 A

中获取 x1 和 x2 的一些值
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)))

eigenvals and eigenvects 方法是这里通常使用的方法。

A.eigenvals() returns {-sqrt(17)/2 - 3/2: 1, -3/2 + sqrt(17)/2: 1} 这是特征值及其重数的字典。如果您不关心多重性,请使用 list(A.eigenvals().keys()) 获取特征值的简单列表。

eigenvects 的输出有点复杂,由三元组组成(特征值、该特征值的重数、特征空间的基)。注意重数是algebraic multiplicity, while the number of eigenvectors returned is the geometric multiplicity,可能更小。由于某种原因,特征向量作为 1 列矩阵返回...

对于您的矩阵,A.eigenvects() returns 特征值 -3/2 + sqrt(17)/2 的特征向量 [-2/(-sqrt(17)/2 + 3/2), 1] 和特征值 -sqrt(17)/2 - 3/2 的特征向量 [-2/(3/2 + sqrt(17)/2), 1]

如果您希望将特征向量呈现为简单的坐标列表,则以下

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

会输出 [[-2/(-sqrt(17)/2 + 3/2), 1], [-2/(3/2 + sqrt(17)/2), 1]]。 (注意这只是为每个特征值选择一个特征向量,这并不总是你想要的)

sympy 有一种非常方便的获取特征值和特征向量的方法:sympy-doc

您的示例将简单地变为:

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

这个答案会帮助你当你所有的特征向量,上面的解决方案并不总是给你所有的特征向量例如下面使用的这个矩阵 A

# 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))