Testing Matrix Matrix Using QuickCheck

I am creating a Matrix module in Haskell, and I want to use QuickCheck to check some properties of my code. In particular, I want to generate random matrices that have a related inverse. Next up is my attempt to create a QuickCheck generator that generates such matrices.

invertibleMatrix :: (Num a, Arbitrary a) => Gen (Matrix a)
invertibleMatrix = do s <- choose (2,10)
                      a <- vectorOf s (vector s)
                      if (det (Matrix a) == 0) then
                        invertibleMatrix
                      else
                        return (Matrix a)

First, the code creates a size from 2 to 10, and then a vector of vectors of that size. If the determinant is zero, then the matrix is ​​not invertible and therefore I call the invertible matrix recursively. Otherwise, I return a new matrix.

The problem is that this code does not end when I put it in a property for verification. (I think that he constantly creates the same sx s-matrix of zero elements, which obviously has no inverse and therefore goes into an infinite loop). What am I doing wrong? How to fix it? Thank.

Mark

+3
source share
3 answers
squareMatrix :: (Num a, Arbitrary a) => Gen (Matrix a)
squareMatrix = do s <- choose (2,6)
                  a <- vectorOf s (vector s)
                  return (Matrix a)

invertibleMatrix :: (Num a, Arbitrary a) => Gen (Matrix a)
invertibleMatrix = suchThat squareMatrix ((/=0) . det) 

In case someone wants to know, this is the solution.

Mark

+1
source

, , A n × n-, A-tI , n t (.. A). , , , , . ( , , , A t, ).

+2

I have not tested this, but I think that the kind of perturbation you want can be taken from the CoArbitrary, which is usually used to implement a random function.

invertibleMatrix :: (Num a, Arbitrary a) => Gen (Matrix a)
invertibleMatrix = kick seed where
  seed :: Integer
  seed = 0
  kick n = do
    s <- choose (2,10)
    a <- vectorOf s (vector s)
    if (det (Matrix a) == 0) then
      coarbitrary (kick (succ n))
    else
      return (Matrix a)
0
source

All Articles