Haskell 矩阵相等失败

标签 haskell matrix equality

我正在尝试使用 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/

相关文章:

c# - 2.5D 矩阵哇音和视频卡

r - 如何将数据帧(或向量)转换为矩阵以将 R 基线包用于除提供的示例数据之外的数据?

python - 列表中的 sympy 点积结果

c# - C# 中相等性的最少代码

haskell - 我怎样才能找到包含我的包的堆栈解析器?

haskell - 未装箱类型的限制

使用 Attoparsec 解析简单的分子名称

swift - 将相等性定义为引用类型的标识?

java - 为什么 hashCode() 在所有连续执行中为对象返回相同的值?

haskell - 使用 aeson 将 unicode 从 JSON 读取到字符串字段