Invalid Haskell Matrix Equality

I use Haskell to implement some quantum transformation matrices. I have a function designed to check if a square matrix is ​​unitary or not by creating inverse and conjugate matrices and then checking both.

The function is shown below, where wrap is a simple function used to check for any value returned from the return.

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 receiving the matrices 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 constructed 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 can lead to an equality check error for the second pair of matrices? Is there a better way to represent complex numbers in code?

+5
source share
1 answer

Double are floating point numbers, and floating point numbers are essentially inaccurate. == will perform an exact equality check, where you are likely to need a "close enough" check.

Alternatively, you can use a different numeric type that either 1) uses unlimited precision (for example, or 2) unlimited memory for unlimited precision. scientific is a good choice, since fixed .

+3
source

Source: https://habr.com/ru/post/1273365/


All Articles