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.rs30 chars3 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.rs210 chars10 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