eig(a,b) in Python giving error “takes 1 positional argument but 2 were given”

♀尐吖头ヾ 提交于 2021-02-08 03:29:00

问题


According to https://docs.scipy.org/doc/numpy-1.15.0/user/numpy-for-matlab-users.html, the equivalent numpy expression for the MATLAB [V,D]=eig(a,b) is V,D = np.linalg.eig(a,b).

But when I try this I get the error:

TypeError: eig() takes 1 positional argument but 2 were given

I'm confused, the documentation says np.linalg.eig can take two arguments?

Curiously, when I look at the linalg documentation at https://docs.scipy.org/doc/numpy-1.15.1/reference/routines.linalg.html, under the heading 'Matrix eigenvalues' there is no mention of linalg.eig taking two arguments?

How can I get eig to take two arguments like in MATLAB?

This works in MATLAB

a = diag(ones(3,1));
b = diag(2*ones(3,1));
[V,D] = eig(a,b)

Output:

V =

    0.7071         0         0
         0    0.7071         0
         0         0    0.7071


D =

    0.5000         0         0
         0    0.5000         0
         0         0    0.5000

This doesn't work in Python

import numpy as np

a = np.diag(np.ones(3))
b = np.diag(2*np.ones(3))

V,D = np.linalg.eig(a,b)

Error:

TypeError: eig() takes 1 positional argument but 2 were given

回答1:


As you saw in the docs of numpy.linalg.eig, it only accepts a single array argument and correspondingly it doesn't compute generalized eigenvalue problems.

Fortunately we have scipy.linalg.eig:

scipy.linalg.eig(a, b=None, left=False, right=True, overwrite_a=False, overwrite_b=False, check_finite=True, homogeneous_eigvals=False)

    Solve an ordinary or generalized eigenvalue problem of a square matrix.

Here's your example case:

import numpy as np 
import scipy.linalg 

a = np.diag(np.ones(3)) 
b = np.diag(2*np.ones(3)) 
eigvals,eigvects = scipy.linalg.eig(a, b) 

Now we have

>>> eigvals
array([0.5+0.j, 0.5+0.j, 0.5+0.j])

>>> eigvects
array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.]])

The difference in the eigenvectors might be due to a different choice in normalization for the eigenvalues. I'd check with two nontrivial matrices and see if the results correspond to one another (comparing corresponding eigenvalue-eigenvector pairs, of course).



来源:https://stackoverflow.com/questions/54191262/eiga-b-in-python-giving-error-takes-1-positional-argument-but-2-were-given

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!