Non-uniform random distribution with Rust and Rand Crate

I have been trying to do generate non-uniform random distribution with Rust and Rand crate, but I wonder if there is an easy way to do this.

suppose I have a vec:

let s =vec![0.8;0.1;0.1]

I want to generate a number from a set, maybe {0,1,2}, so that 80%, it will be 0, 10% it will be 1 and 10% it will be 2, just like the random distribution from the distribution vec.

Seem straightforward but I am unaware if the Rand crate would allow me to do so. I have to create my own function like this:

fn non_uniform_rand(distribution_vec:&Vec<f64>)->usize{
    let mut rng= rand::thread_rng();
    let mut sum=0.0;
    for i in 0..distribution_vec.len(){
        sum+=distribution_vec[i];
    }
    assert_eq!(sum, 1.0);
    for i in 0..distribution_vec.len()-1{
        let random_number=rng.gen_range(0..1000);
        if random_number  < (distribution_vec[i] * 1000.0) as i32{           
            return i
        }
    }
    distribution_vec.len()-1
}

It works but not really elegant. I am looking for anything built into Rand Crate.
Thank you.

Looks like you want rand::distributions::WeightedIndex; the documentation has a usage example.

1 Like