我正在尝试使用 Haskell 来实现一些量子变换矩阵。我有一个函数旨在通过构建逆矩阵和伴随矩阵然后测试两者来测试方阵是否是酉矩阵。
该函数如下所示,其中wrap是一个简单的函数,用于测试inverse返回的Either值。
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
对于一些简单的测试矩阵,它工作得很好,在获取如下所示的矩阵时返回 True:
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) )
我的问题是,该函数对于使用 ((1/sqrt(2) :+ 0) 和 ((-1/sqrt(2)) :+ 0)) 构建的 Hadamard 变换矩阵返回 False
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) )
什么可能导致第二对矩阵的相等测试失败?有没有更正确的方法让我在代码中呈现复数?
最佳答案
Double
是 float ,而 float 本质上是不准确的。 ==
将执行精确的相等性检查,您可能需要“足够接近”的相等性检查。
或者,您可以使用不同的数字类型,1) 具有固定精度(例如,或 2)无限内存使用以获得无限精度。 scientific
是一个不错的选择,就像 fixed
.
关于Haskell 矩阵相等失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47291117/