pub trait Rv<X> {
// Required methods
fn ln_f(&self, x: &X) -> f64;
fn draw<R: Rng>(&self, rng: &mut R) -> X;
// Provided methods
fn f(&self, x: &X) -> f64 { ... }
fn sample<R: Rng>(&self, n: usize, rng: &mut R) -> Vec<X> { ... }
fn sample_stream<'r, R: Rng>(
&'r self,
rng: &'r mut R
) -> Box<dyn Iterator<Item = X> + 'r> { ... }
}
Expand description
Random variable
Contains the minimal functionality that a random object must have to be useful: a function defining the un-normalized density/mass at a point, and functions to draw samples from the distribution.
Required Methods§
Provided Methods§
sourcefn f(&self, x: &X) -> f64
fn f(&self, x: &X) -> f64
Probability function
§Example
use rv::dist::Gaussian;
use rv::traits::Rv;
let g = Gaussian::standard();
assert!(g.f(&0.0_f64) > g.f(&0.1_f64));
assert!(g.f(&0.0_f64) > g.f(&-0.1_f64));
sourcefn sample<R: Rng>(&self, n: usize, rng: &mut R) -> Vec<X>
fn sample<R: Rng>(&self, n: usize, rng: &mut R) -> Vec<X>
Multiple draws of the Rv
§Example
Flip a lot of coins
use rv::dist::Bernoulli;
use rv::traits::Rv;
let b = Bernoulli::uniform();
let mut rng = rand::thread_rng();
let xs: Vec<bool> = b.sample(22, &mut rng);
assert_eq!(xs.len(), 22);
Estimate Gaussian mean
use rv::dist::Gaussian;
use rv::traits::Rv;
let gauss = Gaussian::standard();
let mut rng = rand::thread_rng();
let xs: Vec<f64> = gauss.sample(100_000, &mut rng);
assert::close(xs.iter().sum::<f64>()/100_000.0, 0.0, 1e-2);
sourcefn sample_stream<'r, R: Rng>(
&'r self,
rng: &'r mut R
) -> Box<dyn Iterator<Item = X> + 'r>
fn sample_stream<'r, R: Rng>( &'r self, rng: &'r mut R ) -> Box<dyn Iterator<Item = X> + 'r>
Create a never-ending iterator of samples
§Example
Estimate the mean of a Gamma distribution
use rv::traits::Rv;
use rv::dist::Gamma;
let mut rng = rand::thread_rng();
let gamma = Gamma::new(2.0, 1.0).unwrap();
let n = 1_000_000_usize;
let mean = <Gamma as Rv<f64>>::sample_stream(&gamma, &mut rng)
.take(n)
.sum::<f64>() / n as f64;;
assert::close(mean, 2.0, 1e-2);
Object Safety§
This trait is not object safe.