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)
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With