Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit floats generated by Quickcheck to a range?

Tags:

testing

rust

I would like to generate random floats for Quickcheck that are limited to a certain range such as 0.0 to 1.0 for testing functions working on probabilities. I would like to be able to do something where this would be successful:

quickcheck! {        
    fn prop(x: f64, y: f64) -> bool {
        assert!(x <= 1.0);
        assert!(y <= 1.0);

        (x * y < x) && (x * y < y)
    }
}
like image 905
Alexander Battisti Avatar asked Oct 28 '25 16:10

Alexander Battisti


1 Answers

Create a new type that represents your desired range, then implement quickcheck::Arbitrary for it:

#[macro_use]
extern crate quickcheck;

#[derive(Debug, Copy, Clone)]
struct Probability(f64);

impl quickcheck::Arbitrary for Probability {
    fn arbitrary<G: quickcheck::Gen>(g: &mut G) -> Self {
        Probability(g.gen_range(0.0, 1.0))
    }
}

quickcheck! {
    fn prop(x: Probability, y: Probability) -> bool {
        let x = x.0;
        let y = y.0;

        assert!(x <= 1.0);
        assert!(y <= 1.0);

        (x * y < x) && (x * y < y)
    }
}

Arbitrary is passed a type that implements quickcheck::Gen, which is a light wrapper on top of rand::Rng.

Note that Rng::gen_range has an exclusive upper bound, so this example isn't exactly what you want, but it shows the process.

like image 168
Shepmaster Avatar answered Oct 31 '25 11:10

Shepmaster