Module distr

Generating random samples from probability distributions

Quick start

use rand::RngExt;
let mut rng = rand::rng();

eprintln!("A letter: {}", rng.sample(rand::distr::Alphabetic) as char);

let percent_range = rand::distr::Uniform::try_from(0..=100).unwrap();
eprintln!("Percentage: {}%", rng.sample(&percent_range));

Distribution trait

Abstractly, a probability distribution describes the probability of occurrence of each value in its sample space.

More concretely, a sampler X implementing [Distribution][]<T> is an algorithm for choosing values from the sample space T (or a subset of T) using randomness from an Rng. Typically the sampler X emulates some like-named probability distribution (for example, Bernoulli emulates the Bernoulli distribution).

The Standard Uniform distribution

The StandardUniform distribution is perhaps the most important sampler, representing the "default" probability distribution for a type. Its distribution is expected to be uniform. For bool, char and integer types the sample space equals that of the type (i.e. any valid value of that type may be yielded), but for floating-point types the sample range is arbitrarily set to 0.0..1.0.

Implementing [Distribution<T>] for StandardUniform for type T enables sampling type T using RngExt::random and (by extension) rand::random.

Other standard uniform distributions

Alphanumeric is a simple distribution to sample random letters and numbers of the char type; in contrast StandardUniform may sample any valid char.

There's also an Alphabetic distribution which acts similarly to Alphanumeric but doesn't include digits.

For floats (f32, f64), StandardUniform samples from [0, 1). Also provided are Open01 (samples from (0, 1)) and OpenClosed01 (samples from (0, 1]). No option is provided to sample from [0, 1]; it is suggested to use one of the above half-open ranges since the failure to sample a value which would have a low chance of being sampled anyway is rarely an issue in practice.

Parameterized Uniform distributions

The Uniform distribution provides uniform sampling over a specified range on a subset of the types supported by the above distributions.

Implementations support single-value-sampling via Rng::random_range(Range). Where a fixed (non-const) range will be sampled many times, it is likely faster to pre-construct a Distribution object using Uniform::new, Uniform::new_inclusive or From<Range>.

Non-uniform sampling

Sampling a simple true/false outcome with a given probability has a name: the Bernoulli distribution (this is used by RngExt::random_bool).

For weighted sampling of discrete values see the weighted module.

This crate no longer includes other non-uniform distributions; instead it is recommended that you use either rand_distr or statrs.

Modules

Structs

Enums

Traits