我编写了一些代码,使用 repa计算距离矩阵:
distance :: Int -> Int -> Mat -> Double
distance aindx bindx arr = let a = slice arr (Any :. aindx :. All)
b = slice arr (Any :. bindx :. All)-
sqdiff = R.map (\x -> x*x) $ R.zipWith (-) a b
in sqrt $ sumAllS sqdiff
buildDistanceMatrix :: Mat -> Mat
buildDistanceMatrix m = let (Z :. height :. width) = R.extent m
cords = fromListUnboxed (Z :. (height * height) ) [ (x,y) | x <- [0..height-1], y <- [0..height-1]]
dist = R.smap (\(a,b) -> distance a b m) cords
dmat = R.reshape (Z :. height :. height ) dist
in R.computeS dmat
它似乎工作。但后来我添加了一个快速检查:
prop_distmat :: Double -> Bool
prop_distmat d = let dvec = [d,0,0,0]
dmat = R.fromListUnboxed (Z :. (2::Int) :. (2::Int)) dvec
dist = buildDistanceMatrix dmat
in (R.toList dist) == [0.0, d, d, 0.0 ]
换句话说,被距离 D 分开的两个点应该产生一个看起来像 [0,D,D,0] 的距离矩阵。在我的临时手动测试中,确实如此。但 QuickCheck 很快发现 5.0e-324 的距离会产生 [0,0,0,0] 的距离矩阵
distance matrix *** Failed! Falsifiable (after 2 tests and 1074 shrinks):
5.0e-324
这仅仅是因为双打的精度吗?我是否需要限制 QuickCheck 将发送的可能值?或者这是一个真正的错误?