Random values

Now that we have a way of producing random data, how can we convert it to the type of value we want?

This is a trick question: we need to know both the range we want and the type of distribution of this value (which is what the next section is all about).

The Rng trait

For convenience, all generators automatically implement the Rng trait, which provides short-cuts to a few ways of generating values. This has several convenience functions for producing uniformly distributed values:

  • Rng::gen generates an unbiased (uniform) random value from a range appropriate for the type. For integers this is normally the full representable range (e.g. from 0u32 to std::u32::MAX), for floats this is between 0 and 1, and some other types are supported, including arrays and tuples.

    This method is a convenience wrapper around the Standard distribution, as documented in the next section.

  • Rng::gen_range generates an unbiased random value in the given range

  • Rng::fill and Rng::try_fill are optimised functions for filling any byte or integer slice with random values

It also has convenience functions for producing non-uniform boolean values:

  • Rng::gen_bool generates a boolean with the given probability
  • Rng::gen_ratio also generates a boolean, where the probability is defined via a fraction

Finally, it has a function to sample from arbitrary distributions:


fn main() {
extern crate rand;
use rand::Rng;
let mut rng = rand::thread_rng();

// an unbiased integer over the entire range:
let i: i32 = rng.gen();

// a uniformly distributed value between 0 and 1:
let x: f64 = rng.gen();

// simulate rolling a die:
let roll = rng.gen_range(1..7);

Additionally, the random function is a short-cut to Rng::gen on the thread_rng:

fn main() {
if rand::random() {
    println!("we got lucky!");