logo
pub trait Distribution<T> {
    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> T;

    fn sample_iter<'a, R>(&'a self, rng: &'a mut R) -> DistIter<'a, Self, R, T>Notable traits for DistIter<'a, D, R, T>impl<'a, D, R, T> Iterator for DistIter<'a, D, R, T> where
    D: Distribution<T>,
    R: Rng + 'a, 
type Item = T;

    where
        Self: Sized,
        R: Rng
, { ... } }
Expand description

Types (distributions) that can be used to create a random instance of T.

It is possible to sample from a distribution through both the Distribution and Rng traits, via distr.sample(&mut rng) and rng.sample(distr). They also both offer the sample_iter method, which produces an iterator that samples from the distribution.

All implementations are expected to be immutable; this has the significant advantage of not needing to consider thread safety, and for most distributions efficient state-less sampling algorithms are available.

Required methods

Generate a random value of T, using rng as the source of randomness.

Provided methods

Create an iterator that generates random values of T, using rng as the source of randomness.

Example
use rand::thread_rng;
use rand::distributions::{Distribution, Alphanumeric, Uniform, Standard};

let mut rng = thread_rng();

// Vec of 16 x f32:
let v: Vec<f32> = Standard.sample_iter(&mut rng).take(16).collect();

// String:
let s: String = Alphanumeric.sample_iter(&mut rng).take(7).collect();

// Dice-rolling:
let die_range = Uniform::new_inclusive(1, 6);
let mut roll_die = die_range.sample_iter(&mut rng);
while roll_die.next().unwrap() != 6 {
    println!("Not a 6; rolling again!");
}

Implementations on Foreign Types

Implementors