NumPy:linalg.eig()和linalg.eigh()之间的区别 [英] NumPy: difference between linalg.eig() and linalg.eigh()
问题描述
在Python 3应用程序中,我使用NumPy计算对称实矩阵的特征值和特征向量.
In a Python 3 application I'm using NumPy to calculate eigenvalues and eigenvectors of a symmetric real matrix.
这是我的演示代码:
import numpy as np
a = np.random.rand(3,3) # generate a random array shaped (3,3)
a = (a + a.T)/2 # a becomes a random simmetric matrix
evalues1, evectors1 = np.linalg.eig(a)
evalues2, evectors2 = np.linalg.eigh(a)
除了符号,我使用np.linalg.eig
和np.linalg.eigh
得到了相同的特征向量和特征值.那么,这两种方法有什么区别?
Except for the signs, I got the same eigenvectors and eigenvalues using np.linalg.eig
and np.linalg.eigh
. So, what's the difference between the two methods?
谢谢
编辑:我已在此处 https://docs.scipy.org/doc/numpy/reference/genic/numpy.linalg.eig.html
在这里 https://docs.scipy.org/doc /numpy/reference/generation/numpy.linalg.eigh.html
但是我仍然不明白为什么当我有对称数组时为什么应该使用eigh()
.
I've read the docs here https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.eig.html
and here https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.eigh.html
but still I can not understand why I should use eigh()
when I have a symmetric array.
推荐答案
eigh
向您保证特征值已排序,并使用更快的算法来利用矩阵对称的事实. 如果您知道矩阵是对称的,请使用此函数.
注意,eigh
不会检查矩阵是否确实对称,默认情况下,它仅取矩阵的下三角部分,并假定上三角部分由矩阵的对称性定义
eigh
guarantees you that the eigenvalues are sorted and uses a faster algorithm that takes advantage of the fact that the matrix is symmetric. If you know that your matrix is symmetric, use this function.
Attention, eigh
doesn't check if your matrix is indeed symmetric, it by default just takes the lower triangular part of the matrix and assumes that the upper triangular part is defined by the symmetry of the matrix.
eig
适用于一般矩阵,因此使用较慢的算法,例如,可以使用IPython的魔术命令%timeit
进行检查.如果使用更大的矩阵进行测试,您还将看到一般而言,特征值不在此处排序.
eig
works for general matrices and therefore uses a slower algorithm, you can check that for example with IPythons magic command %timeit
. If you test with larger matrices, you will also see that in general the eigenvalues are not sorted here.
这篇关于NumPy:linalg.eig()和linalg.eigh()之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!