#random #randomly #samples #choice #choose #chooses #weights-probabilities

random_choice

Chooses samples randomly by their weights/probabilities

6 releases

Uses old Rust 2015

0.3.2 Aug 26, 2016
0.3.1 Aug 25, 2016
0.2.0 Jul 27, 2016
0.1.1 Jul 24, 2016

#1298 in Algorithms

Download history 6754/week @ 2023-11-20 6025/week @ 2023-11-27 11460/week @ 2023-12-04 6269/week @ 2023-12-11 5558/week @ 2023-12-18 334/week @ 2023-12-25 5407/week @ 2024-01-01 7978/week @ 2024-01-08 7008/week @ 2024-01-15 5761/week @ 2024-01-22 4875/week @ 2024-01-29 6067/week @ 2024-02-05 6650/week @ 2024-02-12 3739/week @ 2024-02-19 10626/week @ 2024-02-26 11777/week @ 2024-03-04

32,816 downloads per month
Used in 5 crates (3 directly)

Apache-2.0

8KB
69 lines

Rust Random Choice

Chooses samples randomly by their weights/probabilities.

Advantages

  • There is a good diversity for the case that all weights are equally distributed (in contrast to the roulette wheel selection algorithm)
  • Blazingly fast: O(n) (Roulette wheel selection algorithm: O(n * log n))
  • Memory Usage: O(n)
  • The sum of the weights don't have to be 1.0, but must not overflow

This algorithm is based on the stochastic universal sampling algorithm.

Applications

  • Evolutionary algorithms: Choose the n fittest populations by their fitness fi
  • Monte Carlo Localization: Resampling of n particles by their weight w

Usage

Add this to your Cargo.toml:

[dependencies]
random_choice = "*"

Examples

Default Way

extern crate random_choice;
use self::random_choice::random_choice;

fn main() {
    let mut samples = vec!["hi", "this", "is", "a", "test!"];
    let weights: Vec<f64> = vec![5.6, 7.8, 9.7, 1.1, 2.0];

    let number_choices = 100;
    let choices = random_choice().random_choice_f64(&samples, &weights, number_choices);

    for choice in choices {
        print!("{}, ", choice);
    }
}

With Custom Seed

extern crate rand;
extern crate random_choice;
use random_choice::RandomChoice;
use rand::SeedableRng;

fn main() {
    let mut samples = vec!["hi", "this", "is", "a", "test!"];
    let weights: Vec<f64> = vec![5.6, 7.8, 9.7, 1.1, 2.0];

    let rng = rand::StdRng::from_seed(&[5000, 44, 55, 199]);

    let mut random_choice = RandomChoice::new(rng);
    let number_choices = 100;
    let choices = random_choice.random_choice_f64(&mut samples, &weights, number_choices);

    for choice in choices {
        print!("{}, ", choice);
    }
}

Dependencies

~325–550KB