问题
I had to check whether a matrix had eigenvalue with multiplicity>1 or not. Using numpy's eig function I got an array and converted it into set,which should remove the repeated eigenvalue and comparing the length of the list and the set,we can infer whether whether there are repeated eigenvalues or not.The code is given below-
from numpy.linalg import eig
A=[[3,1,1],[2,4,2],[-1,-1,1]]
if len(eig(A)[0])!=len(set(eig(A)[0])):
print "Multiple eigenvalues found!"
else:
print "All distinct"
I got the result as "All distinct",and to check i did-print set(eig(A)[0])
and got
>>>set([2.0000000000000009, 1.9999999999999998, 3.9999999999999982])
The eigenvalues are 2,2,4 and the set operation must make it {2,4}.But it is converting one 2 into 2.0000000000000009 and another into 1.9999999999999998,and making them appear distinct.
I know,there can be other longer methods using loop/counter for checking distinctness of eigenvalues,but Why is this happening?
回答1:
As suggested by @JohanC, you can use the sympy library, in particular here a possible implementation:
from sympy import Matrix
import numpy as np
A=[[3,1,1], [2,4,2], [-1,-1,1]]
M = Matrix(A)
# Create array with eigenvalues multiplicities
mults = np.array([m for m in M.eigenvals().values()])
if np.any(mults>1):
print("Multiple eigenvalues found!")
else:
print("All distinct")
回答2:
I just found out that this can also be done without using numpy by converting the float/complex values into string and comparing the strings(though not very efficient)-
from numpy.linalg import eig
A=[[3,1,1],[2,4,2],[-1,-1,1]]
if len(set([str(elem) for elem in eig(A)[0]]))!=len([str(elem) for elem in eig(A)[0]]):
print "Multiple eigenvalues found!"
else:
print "All distinct"
来源:https://stackoverflow.com/questions/60914705/why-is-set-function-on-a-numpy-array-returning-slightly-different-values