Reputation: 1094
I am using Python 2.7, NumPy 1.6.2 and SciPy 0.16.0 to calculate the following.
I have created a Hadamard matrix. Then I have created outer products from the 0,2,4-th vectors of the matrix and added them and made the diagonal 0. Then I have computed the eigenvalues using SciPy.linalg.eigh(). It is degenerate. First two eigenvalues are same, i.e., -3. But when I use Python to check it says they are not same. The code is given below.
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]
The output is:
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
What I am doing wrong?
Upvotes: 2
Views: 955
Reputation: 222461
When working with floats, always be careful with equal operator and remember that there might be precision problems and 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])
By the way, it returned true in both cases on my machine:
-3.0 == -3.0?
True
True
Upvotes: 2