How to generate probabilities in FsCheck

I would like to check a property in which I use 2 probabilities p1 and p2 which must satisfy 0 <p1 <p2 <1

let arraySizeCheck (p1:float, p2:float, xs:list<int>) =
(p1 < p2 && p1 > 0.0 && p1 < 1.0 && p2 > 0.0 && p2 < 1.0 && Seq.length xs > 0) ==>
(lazy
    (
        let bf1 = BloomFilter(p1, xs)
        let bf2 = BloomFilter(p2, xs)
        bf2.BitArraySize < bf1.BitArraySize
    )
)

Check.Quick arraySizeCheck

      

I tried the above example, but the test result seems to be

Arguments exhausted after 0 tests. val it: unit = ()

Also, I would prefer that the xs list does not contain duplicates. Any help writing a test case for this property would be appreciated. Thank.

+3


source to share


1 answer


A more idiomatic approach would be to use expression functions and combinator functions gen

from a module gen

. Unfortunately, the function that returns a generator that generates a random floating point number is hidden (see source code .)

But we can create our own:



open System
open FsCheck
open FsCheck.Gen
open FsCheck.Prop

/// Generates a random float [0..1.0]
let rand = Gen.choose (0, Int32.MaxValue) |> Gen.map (fun x -> double x / (double Int32.MaxValue))

/// Generates a random float in the given range (inclusive at both sides)
let randRange a b = rand |> Gen.map (fun x -> a + (b - a) * x)

let arraySizeCheck =
    Prop.forAll
        (Arb.fromGen <| gen {
            // generate p1 and p2 such that 0 <= p1 <= p2 <= 1
            let! p1 = randRange 0.0 1.0
            let! p2 = randRange p1 1.0

            // generate non-empty Seq<int>
            let! xs = Gen.nonEmptyListOf Arb.generate<int> |> Gen.map Seq.ofList

            return BloomFilter(p1, xs), BloomFilter(p2, xs)
        })
        (fun (bf1, bf2) -> bf2.BitArraySize < bf1.BitArraySize)

Check.Quick arraySizeCheck

      

Note that p1

and p2

are created so that 0 <= p1 <= p2 <= 1

that is not exactly what you need. But I think a simple modification of the function rand

can fix this.

+1


source







All Articles