Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell Matrix equality failing

I'm messing around with using Haskell for implementing some quantum transformation matrices. I have a function designed to test if a square matrix is unitary or not by building the inverse and adjoint matrices and then testing both.

The function is shown below, where wrap is a simple function used to test the Either value returned from inverse.

isUnitary :: [[Copmlex Double]] -> Bool
isUnitary lists = let mat =  fromLists lists --Create matrix from lists
                      conjugateTranspose = fmap conjugate $ Data.Matrix.transpose mat --Conjugate Transpose Matrix
                      inverseMat = debug("ConjugateTranspose: \n" ++ show conjugateTranspose ++ "\n")
                                    wrap $ inverse mat --The inverse matrix
                      in if (conjugateTranspose) == inverseMat then debug("InverseMat: \n" ++ show inverseMat ++ "\n")
                                                                      True
                         else debug("InverseMat: \n" ++ show inverseMat ++ "\n")
                                False

For some simple test matrices it works fine, returning True when getting the matrices shown below:

ConjugateTranspose:
(    1.0 :+ (-0.0)                   0.0 :+ (-0.0) )
(    0.0 :+ (-0.0)                   (-1.0) :+ (-0.0) )

InverseMat:
(    1.0 :+ 0.0                      0.0 :+ 0.0 )
(    0.0 :+ (-0.0)                   (-1.0) :+ (-0.0) )

My problem is that the function returns False for the Hadamard transform matrix built by using ((1/sqrt(2) :+ 0) and ((-1/sqrt(2)) :+ 0))

ConjugateTranspose:
(    0.7071067811865475 :+ (-0.0)    0.7071067811865475 :+ (-0.0) )
(    0.7071067811865475 :+ (-0.0)    (-0.7071067811865475) :+ (-0.0) )

InverseMat:
(    0.7071067811865476 :+ 0.0       0.7071067811865476 :+ 0.0 )
(    0.7071067811865476 :+ 0.0       (-0.7071067811865476) :+ (-0.0) )

What could be causing the equality test for the second pair of matrices to fail? Is there a more correct way for me to present the complex numbers in the code?

like image 839
E.Zanca Avatar asked Oct 18 '22 03:10

E.Zanca


1 Answers

Double are floating point numbers, and floating point numbers are inherently inaccurate. == is going to perform an exact equality check, where you likely want a "close enough" equality check.

Alternatively, you can use a different numeric type that either 1) has fixed precision (like , or 2) unbounded memory use for unlimited precision. scientific is a good choice, as is fixed.

like image 53
ephrion Avatar answered Oct 21 '22 00:10

ephrion