# [−][src]Module rand::distributions

Generating random samples from probability distributions.

This module is the home of the [`Distribution`] trait and several of its implementations. It is the workhorse behind some of the convenient functionality of the [`Rng`] trait, including `gen`, `gen_range` and of course `sample`.

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

More concretely, an implementation of `Distribution<T>` for type `X` is an algorithm for choosing values from the sample space (a subset of `T`) according to the distribution `X` represents, using an external source of randomness (an RNG supplied to the `sample` function).

A type `X` may implement `Distribution<T>` for multiple types `T`. Any type implementing [`Distribution`] is stateless (i.e. immutable), but it may have internal parameters set at construction time (for example, `Uniform` allows specification of its sample space as a range within `T`).

# The `Standard` distribution

The `Standard` distribution is important to mention. This is the distribution used by [`Rng::gen()`] and represents the "default" way to produce a random value for many different types, including most primitive types, tuples, arrays, and a few derived types. See the documentation of `Standard` for more details.

Implementing `Distribution<T>` for `Standard` for user types `T` makes it possible to generate type `T` with [`Rng::gen()`], and by extension also with the [`random()`] function.

# Distribution to sample from a `Uniform` range

The `Uniform` distribution is more flexible than `Standard`, but also more specialised: it supports fewer target types, but allows the sample space to be specified as an arbitrary range within its target type `T`. Both `Standard` and `Uniform` are in some sense uniform distributions.

Values may be sampled from this distribution using [`Rng::gen_range`] or by creating a distribution object with `Uniform::new`, `Uniform::new_inclusive` or `From<Range>`. When the range limits are not known at compile time it is typically faster to reuse an existing distribution object than to call [`Rng::gen_range`].

User types `T` may also implement `Distribution<T>` for `Uniform`, although this is less straightforward than for `Standard` (see the documentation in the `uniform` module. Doing so enables generation of values of type `T` with [`Rng::gen_range`].

# Other distributions

There are surprisingly many ways to uniformly generate random floats. A range between 0 and 1 is standard, but the exact bounds (open vs closed) and accuracy differ. In addition to the `Standard` distribution Rand offers `Open01` and `OpenClosed01`. See "Floating point implementation" section of `Standard` documentation for more details.

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

`WeightedIndex` can be used to do weighted sampling from a set of items, such as from an array.

# Non-uniform probability distributions

Rand currently provides the following probability distributions:

- Related to real-valued quantities that grow linearly (e.g. errors, offsets):
  - `Normal` distribution, and `StandardNormal` as a primitive
  - `Cauchy` distribution
- Related to Bernoulli trials (yes/no events, with a given probability):
  - `Binomial` distribution
  - `Bernoulli` distribution, similar to [`Rng::gen_bool`].
- Related to positive real-valued quantities that grow exponentially (e.g. prices, incomes, populations):
  - `LogNormal` distribution
- Related to the occurrence of independent events at a given rate:
  - `Pareto` distribution
  - `Poisson` distribution
  - `Exp`onential distribution, and `Exp1` as a primitive
  - `Weibull` distribution
- Gamma and derived distributions:
  - `Gamma` distribution
  - `ChiSquared` distribution
  - `StudentT` distribution
  - `FisherF` distribution
- Triangular distribution:
  - `Beta` distribution
  - `Triangular` distribution
- Multivariate probability distributions
  - `Dirichlet` distribution
  - `UnitSphereSurface` distribution
  - `UnitCircle` distribution

# Examples

Sampling from a distribution:

    use rand::{thread_rng, Rng};
    use rand::distributions::Exp;

    let exp = Exp::new(2.0);
    let v = thread_rng().sample(exp);
    println!("{} is from an Exp(2) distribution", v);

Implementing the `Standard` distribution for a user type:

    use rand::Rng;
    use rand::distributions::{Distribution, Standard};

    struct MyF32 {
        x: f32,
    }

    impl Distribution<MyF32> for Standard {
        fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> MyF32 {
            MyF32 { x: rng.gen() }
        }
    }

## Modules

uniform | A distribution uniformly sampling numbers within a given range.

## Structs

Alphanumeric | Sample a `char`, uniformly distributed over ASCII letters and numbers: a-z, A-Z and 0-9.
Bernoulli | The Bernoulli distribution.
Beta | The Beta distribution with shape parameters `alpha` and `beta`.
Binomial | The binomial distribution `Binomial(n, p)`.
Cauchy | The Cauchy distribution `Cauchy(median, scale)`.
ChiSquared | The chi-squared distribution `χ²(k)`, where `k` is the degrees of freedom.
Dirichlet | The dirichelet distribution `Dirichlet(alpha)`.
DistIter | An iterator that generates random values of `T` with distribution `D`, using `R` as the source of randomness.
Exp | The exponential distribution `Exp(lambda)`.
Exp1 | Samples floating-point numbers according to the exponential distribution, with rate parameter `λ = 1`. This is equivalent to `Exp::new(1.0)` or sampling with `-rng.gen::<f64>().ln()`, but faster.
FisherF | The Fisher F distribution `F(m, n)`.
Gamma | The Gamma distribution `Gamma(shape, scale)` distribution.
LogNormal | The log-normal distribution `ln N(mean, std_dev**2)`.
Normal | The normal distribution `N(mean, std_dev**2)`.
Open01 | A distribution to sample floating point numbers uniformly in the open interval `(0, 1)`, i.e. not including either endpoint.
OpenClosed01 | A distribution to sample floating point numbers uniformly in the half-open interval `(0, 1]`, i.e. including 1 but not 0.
Pareto | Samples floating-point numbers according to the Pareto distribution
Poisson | The Poisson distribution `Poisson(lambda)`.
Standard | A generic random value distribution, implemented for many primitive types. Usually generates values with a numerically uniform distribution, and with a range appropriate to the type.
StandardNormal | Samples floating-point numbers according to the normal distribution `N(0, 1)` (a.k.a. a standard normal, or Gaussian). This is equivalent to `Normal::new(0.0, 1.0)` but faster.
StudentT | The Student t distribution, `t(nu)`, where `nu` is the degrees of freedom.
Triangular | The triangular distribution.
Uniform | Sample values uniformly between two bounds.
UnitCircle | Samples uniformly from the edge of the unit circle in two dimensions.
UnitSphereSurface | Samples uniformly from the surface of the unit sphere in three dimensions.
Weibull | Samples floating-point numbers according to the Weibull distribution
Weighted | Deprecated A value with a particular weight for use with `WeightedChoice`.
WeightedChoice | Deprecated A distribution that selects from a finite collection of weighted items.
WeightedIndex | A distribution using weighted sampling to pick a discretely selected item.

## Enums

WeightedError | Error type returned from `WeightedIndex::new`.

## Traits

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

# Help

## Keyboard Shortcuts

`?`
  Show this help dialog
`S`
  Focus the search field
`↑`
  Move up in search results
`↓`
  Move down in search results
`↹`
  Switch tab
`⏎`
  Go to active search result
`+`
  Expand all sections
`-`
  Collapse all sections

## Search Tricks

Prefix searches with a type followed by a colon (e.g., `fn:`) to restrict the search to a given type.

Accepted types are: `fn`, `mod`, `struct`, `enum`, `trait`, `type`, `macro`, and `const`.

Search functions by type signature (e.g., `vec -> usize` or `* -> vec`)

Search multiple things at once by splitting your query with comma (e.g., `str,u8` or `String,struct:Vec,test`)