pub struct VoseAlias<T>{
pub elements: Vec<T>,
pub alias: HashMap<T, T>,
pub prob: HashMap<T, f32>,
/* private fields */
}Expand description
A structure containing the necessary Vose-Alias tables.
The structure contains the following attributes:
- A vector containing the elements to sample frmo
- The Alias table, created from the Vose-Alias initialization step
- The Probability table, created frmo the Vose-Alias initialization step
The structure is created by the function vose_alias::new(). See its documentation for more details.
Internally, the elements are used as indexes in HashMap and Vec. Therefore, the type T must implement the following traits:
- Copy
- Hash
- Eq
- Debug
Fields§
§elements: Vec<T>§alias: HashMap<T, T>§prob: HashMap<T, f32>Implementations§
Source§impl<T> VoseAlias<T>
impl<T> VoseAlias<T>
Sourcepub fn new(element_vector: Vec<T>, probability_vector: Vec<f32>) -> VoseAlias<T>
pub fn new(element_vector: Vec<T>, probability_vector: Vec<f32>) -> VoseAlias<T>
Returns the Vose-Alias object containing the element vector as well as the alias and probability tables.
The element_vector contains the list of elements that should be sampled from.
The probability_vector contains the probability distribution to be sampled with.
element_vector and probability_vector should have the same size and probability_vector should describe a well-formed probability distribution.
§Panics
The function panics in two casese:
- the
element_vectorand theprobability_vectordo not contain the same number of elements - the sum of the elements in
probability_vectoris not equal to 1 (with a floating number precision of 0.0001), meaning thatprobability_vectordoes not describe a well formed probability distribution
§Examples
use vose_alias::VoseAlias;
// Creates a Vose-Alias object from a list of Integer elements
let va = VoseAlias::new(vec![1, 2, 3, 4], vec![0.5, 0.2, 0.2, 0.1]);Sourcepub fn sample(&self) -> T
pub fn sample(&self) -> T
Returns a sampled element from a previously created Vose-Alias object.
This function uses a VoseAlias object previously created using the method vose_alias::new() to sample in linear time an element of type T.
§Panics
This function panics only if the lists created in vose_alias::new() are not correctly form, which would indicate a internal bug in the code.
If your code panics while using this function, please fill in an issue report.
§Examples
use vose_alias::VoseAlias;
// Samples an integer from a list and prints it.
let va = VoseAlias::new(vec![1, 2, 3, 4], vec![0.5, 0.2, 0.2, 0.1]);
let element = va.sample();
println!("{}", element);