Skip to main content
 首页 » 编程设计

python之相同的 SciPy.linalg.eigh() 特征值不相等

2024年10月24日15TianFang

我正在使用 Python 2.7、NumPy 1.6.2 和 SciPy 0.16.0 来计算以下内容。

我创建了一个 Hadamard 矩阵。然后我从矩阵的第 0、2、4 个向量创建外积并将它们相加并使对角线为 0。然后我使用 SciPy.linalg.eigh() 计算了特征值。它是退化的。前两个特征值相同,即 -3。但是当我使用 Python 检查时,它说它们不一样。代码如下。

from scipy import linalg as sp 
import numpy 
from numpy import linalg as np 
 
def get_outer_product(vector): 
    length = len(vector) 
 
    outer_product = [[0 for x in range(length)] for x in range(length)] 
 
    for i in range(0, length): 
        for j in range(0, length): 
            if i == j: 
                outer_product[i][j] = 0 
                continue 
            outer_product[i][j] = vector[i] * vector[j] 
    return outer_product 
 
def test(): 
    hadamard_matrix = sp.hadamard(8) 
    sum_of_outer_products = [map(sum, zip(*t)) for t in zip(get_outer_product(hadamard_matrix[0]), get_outer_product(hadamard_matrix[2]))] 
    sum_of_outer_products = [map(sum, zip(*t)) for t in zip(sum_of_outer_products, get_outer_product(hadamard_matrix[4]))] 
 
    e_vals, e_vecs = sp.eigh(sum_of_outer_products) 
    print str(e_vals[0]) + " == " + str(e_vals[0]) + "?" 
    print e_vals[0] == e_vals[1] 

输出是:

Python 2.7 (r27:82525, Jul  4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] on win32 
>>> import scipytest 
>>> scipytest.test() 
-3.0 == -3.0? 
False 

我做错了什么?

请您参考如下方法:

Floating point problem .

使用 float 时,始终小心等于运算符并记住可能存在精度问题和 use safe comparison :

print str(e_vals[0]) + " == " + str(e_vals[0]) + "?" 
print e_vals[0] == e_vals[1] 
print numpy.isclose(e_vals[0], e_vals[1]) 

顺便说一句,在我的机器上,它在两种情况下都返回了 true:

-3.0 == -3.0? 
True 
True