为什么在numpy数组上的set函数返回略有不同的值? [英] Why is set function on a numpy array returning slightly different values?

查看:90
本文介绍了为什么在numpy数组上的set函数返回略有不同的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须检查矩阵是否具有多重性大于1的特征值. 使用numpy的eig函数,我得到了一个数组并将其转换为集合,该集合应删除重复的特征值并比较列表和集合的长度,我们可以推断是否存在重复的特征值.代码在下面给出-

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"

我得到的结果为所有不同",并检查我是否做到了-print set(eig(A)[0])并得到

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]) 特征值是2、2、4,并且设置操作必须使其为{2,4}.但是它将一个2转换为2.0000000000000009,将另一个2转换为1.9999999999999998,并使它们看起来不同.

>>>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?

推荐答案

如@JohanC所建议的,您可以使用sympy库,特别是这里可能的实现方式:

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

这篇关于为什么在numpy数组上的set函数返回略有不同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆