distribution
import std::random::distribution; · source
Distribution<T>
type trait Distribution<T> {
sample<R>(&this, rng: mut &R) -> T
where R: RandomSource;
}
A Distribution<T> turns a source of random bits into draws of a particular shape. sample(rng) is generic over R: RandomSource, so every distribution works with Rng, SecureRng, or a custom source.
| Distribution | Produces |
|---|---|
UniformU64::new(lo, hi) | u64 in [lo, hi) |
UniformI64::new(lo, hi) | i64 in [lo, hi) |
UniformF64::new(lo, hi) | f64 in [lo, hi) |
Bernoulli::new(p) | boolean — true with probability p, clamped to [0, 1] |
Normal::new(mean, std_dev) | f64 |
Exponential::new(lambda) | f64 — waiting times at rate lambda, mean 1 / lambda |
WeightedIndex::try_new(weights) | u64 — an index chosen in proportion to its weight |
import std::random::distribution;
const d: Normal = Normal::new(0.0, 1.0);
const z: f64 = d.sample(&r);
The distributions
UniformU64, UniformI64, and UniformF64
type struct UniformU64 {
lo: u64;
hi: u64;
static new(lo: u64, hi: u64) -> UniformU64;
}
type struct UniformI64 {
lo: i64;
hi: i64;
static new(lo: i64, hi: i64) -> UniformI64;
}
type struct UniformF64 {
lo: f64;
hi: f64;
static new(lo: f64, hi: f64) -> UniformF64;
}
A value in [lo, hi), uniformly. The integer forms use the same unbiased rejection sampling as next_below; the float form scales a 53-bit draw.
Bernoulli
type struct Bernoulli {
p: f64;
static new(p: f64) -> Bernoulli;
}
true with probability p, clamped to [0, 1].
Normal and Exponential
type struct Normal {
mean: f64;
std_dev: f64;
static new(mean: f64, std_dev: f64) -> Normal;
}
type struct Exponential {
lambda: f64;
static new(lambda: f64) -> Exponential;
}
Normal is a Box–Muller draw around mean with std_dev; Exponential gives waiting times at rate lambda, mean 1 / lambda.
WeightedIndex
type struct WeightedIndex {
cumulative: Array<f64>;
total: f64;
static try_new(weights: Slice<f64>) -> Result<WeightedIndex, RandomError>;
length(&this) -> u64;
}
WeightedIndex is built once from a weight list and then sampled cheaply. It owns its cumulative table, so it carries a drop, and construction is fallible: InvalidWeights when the list is empty, contains a negative entry, or sums to zero.
Trait implementations
implement trait Distribution<u64> for struct UniformU64
implement trait Distribution<i64> for struct UniformI64
implement trait Distribution<f64> for struct UniformF64
implement trait Distribution<boolean> for struct Bernoulli
implement trait Distribution<f64> for struct Normal
implement trait Distribution<f64> for struct Exponential
implement trait Distribution<u64> for struct WeightedIndex
implement trait Drop for struct WeightedIndex