eigenvalue and eigenvectors in python vs matlab

醉酒当歌 提交于 2019-12-01 09:42:45

To get NumPy to return a diagonal array of real eigenvalues when the complex part is small, you could use

In [116]: np.real_if_close(np.diag(w))
Out[116]: 
array([[ 4.,  0.,  0.],
       [ 0., -2.,  0.],
       [ 0.,  0., -2.]])

According to the Matlab docs, [E, D] = eig(A) returns E and D which satisfy A*E = E*D: I don't have Matlab, so I'll use Octave to check the result you posted:

octave:1> A = [[1, -3, 3],
               [3, -5, 3],
               [6, -6, 4]]

octave:6> E = [[ -0.4082, -0.8103, 0.1933],
               [ -0.4082, -0.3185, -0.5904],
               [ -0.8165, 0.4918, -0.7836]]

octave:25> D = [[4.0000, 0, 0],
               [0, -2.0000, 0],
               [0, 0, -2.0000]]

octave:29> abs(A*E - E*D)
ans =

   3.0000e-04   0.0000e+00   3.0000e-04
   3.0000e-04   2.2204e-16   3.0000e-04
   0.0000e+00   4.4409e-16   6.0000e-04

The magnitude of the errors is mainly due to the values reported by Matlab being displayed to a lower precision than the actual values Matlab holds in memory.


In NumPy, w, v = np.linalg.eig(A) returns w and v which satisfy np.dot(A, v) = np.dot(v, np.diag(w)):

In [113]: w, v = np.linalg.eig(A)

In [135]: np.set_printoptions(formatter={'complex_kind': '{:+15.5f}'.format})

In [136]: v
Out[136]: 
array([[-0.40825+0.00000j, +0.24400-0.40702j, +0.24400+0.40702j],
       [-0.40825+0.00000j, -0.41622-0.40702j, -0.41622+0.40702j],
       [-0.81650+0.00000j, -0.66022+0.00000j, -0.66022-0.00000j]])

In [116]: np.real_if_close(np.diag(w))
Out[116]: 
array([[ 4.,  0.,  0.],
       [ 0., -2.,  0.],
       [ 0.,  0., -2.]])

In [112]: np.abs((np.dot(A, v) - np.dot(v, np.diag(w))))
Out[112]: 
array([[4.44089210e-16, 3.72380123e-16, 3.72380123e-16],
       [2.22044605e-16, 4.00296604e-16, 4.00296604e-16],
       [8.88178420e-16, 1.36245817e-15, 1.36245817e-15]])

In [162]: np.abs((np.dot(A, v) - np.dot(v, np.diag(w)))).max()
Out[162]: 1.3624581677742195e-15

In [109]: np.isclose(np.dot(A, v), np.dot(v, np.diag(w))).all()
Out[109]: True
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!