get a uniformly distributed random number in rust

To get a uniformly distributed random number in Rust, you can use the rand crate.

First, add rand as a dependency in your Cargo.toml file:

main.rs
[dependencies]
rand = "0.8.4"
30 chars
3 lines

Then, in your Rust code, you can generate a random f64 between 0 and 1 using the thread_rng function to get a random number generator, and then the gen_range method to generate the random number:

main.rs
use rand::Rng;
use rand::distributions::Uniform;

fn main() {
    let mut rng = rand::thread_rng();
    let range = Uniform::new(0.0, 1.0);
    let rand_val = rng.sample(range);
    println!("{}", rand_val);
}
210 chars
10 lines

Here, we first create a Uniform distribution that generates numbers between 0 and 1 (excluding 1). We then use the sample method on the random number generator to generate a random number with this distribution, which we store in the rand_val variable.

Finally, we print the rand_val using println! to verify that it is indeed a uniformly distributed random number between 0 and 1.

gistlibby LogSnag