Function rv::misc::ln_pflip

source ·
pub fn ln_pflip<R: Rng>(
    ln_weights: &[f64],
    n: usize,
    normed: bool,
    rng: &mut R
) -> Vec<usize>
Expand description

Draw an index according to log-domain weights

Draw a usize from the categorical distribution defined by ln_weights. If normed is true then exp(ln_weights) is assumed to sum to 1.

§Examples

use rv::misc::ln_pflip;

let weights: Vec<f64> = vec![0.4, 0.2, 0.3, 0.1];
let ln_weights: Vec<f64> = weights.iter().map(|&w| w.ln()).collect();

let xs = ln_pflip(&ln_weights, 100, true, &mut rand::thread_rng());

assert_eq!(xs.len(), 100);
assert!(xs.iter().all(|&x| x <= 3));
assert!(!xs.iter().any(|&x| x > 3));

Can handle -Inf ln weights

use std::f64::NEG_INFINITY;
use std::f64::consts::LN_2;

let ln_weights: Vec<f64> = vec![-LN_2, NEG_INFINITY, -LN_2];

let xs = ln_pflip(&ln_weights, 100, true, &mut rand::thread_rng());

let zero_count = xs.iter().filter(|&&x| x == 0).count();
let one_count = xs.iter().filter(|&&x| x == 1).count();
let two_count = xs.iter().filter(|&&x| x == 2).count();

assert!(zero_count > 30);
assert_eq!(one_count, 0);
assert!(two_count > 30);