Crate rand_array_iid

Source
Expand description

This crates exposes a single struct, IIDDistr, parametrized by a Distribution D.

If D is a Distribution<T> (meaning that it can be used to sample random variate of type T) then IIDDistr<D> is a Distribution<[T;n]> for n between 0 and 31 included (by default), and up to 512 included if the feature more_array_sizes is activated. IIDDistr<D> can be used to sample arrays whose elements are Independently Identically Distributed (i.i.d.) according to D.

§Handling of panic

If sampling from the underlying distributon D panics, sampling from IIDDistr<D> panics as well, but no memory is leaked. This guarantee actually comes from the array_init crate.

§Examples

§An array of normally distributed scalars

let distr = IIDDistr::new(StandardNormal);
let mut rng = rand::thread_rng();
// Each of x element is distributed according to StandardNormal.
let x : [f64; 10] = distr.sample(&mut rng);

§An array of 3D vectors sampled from the unit sphere

let distr = IIDDistr::new(UnitSphere);
let mut rng = rand::thread_rng();
// Each of x element is sampled uniformly from the surface of the 3D unit sphere.
let x : [[f64; 3]; 10] = distr.sample(&mut rng);

§Why only arrays?

Collections such as [Vec] that implement [std::iter::FromIterator] bear no information on their size in their type, hence the distribution would have to be restricted to a given size. They can also be sampled as follow:

fn sample_iid<D,R, Col>(dist: D, rng: &mut R, n: usize) -> Col
where
    R: Rng + ?Sized,
    Col: std::iter::IntoIterator,
    Col: std::iter::FromIterator<<Col as std::iter::IntoIterator>::Item>,
    D: Distribution<<Col as std::iter::IntoIterator>::Item>,
{
    dist.sample_iter(rng).take(n).collect()
}

Structs§

  • A distribution on arrays whose elements are i.i.d. with distribution D.

Constants§