# Struct rand_distr::weighted_tree::WeightedTreeIndex

source · `pub struct WeightedTreeIndex<W: Clone + PartialEq + PartialOrd + SampleUniform + SubAssign<W> + Weight> { /* private fields */ }`

## Expand description

A distribution using weighted sampling to pick a discretely selected item.

Sampling a `WeightedTreeIndex<W>`

distribution returns the index of a randomly
selected element from the vector used to create the `WeightedTreeIndex<W>`

.
The chance of a given element being picked is proportional to the value of
the element. The weights can have any type `W`

for which an implementation of
`Weight`

exists.

## §Key differences

The main distinction between `WeightedTreeIndex<W>`

and `rand::distributions::WeightedIndex<W>`

lies in the internal representation of weights. In `WeightedTreeIndex<W>`

,
weights are structured as a tree, which is optimized for frequent updates of the weights.

## §Caution: Floating point types

When utilizing `WeightedTreeIndex<W>`

with floating point types (such as f32 or f64),
exercise caution due to the inherent nature of floating point arithmetic. Floating point types
are susceptible to numerical rounding errors. Since operations on floating point weights are
repeated numerous times, rounding errors can accumulate, potentially leading to noticeable
deviations from the expected behavior.

Ideally, use fixed point or integer types whenever possible.

## §Performance

A `WeightedTreeIndex<W>`

with `n`

elements requires `O(n)`

memory.

Time complexity for the operations of a `WeightedTreeIndex<W>`

are:

- Constructing: Building the initial tree from an iterator of weights takes
`O(n)`

time. - Sampling: Choosing an index (traversing down the tree) requires
`O(log n)`

time. - Weight Update: Modifying a weight (traversing up the tree), requires
`O(log n)`

time. - Weight Addition (Pushing): Adding a new weight (traversing up the tree), requires
`O(log n)`

time. - Weight Removal (Popping): Removing a weight (traversing up the tree), requires
`O(log n)`

time.

## §Example

```
use rand_distr::WeightedTreeIndex;
use rand::prelude::*;
let choices = vec!['a', 'b', 'c'];
let weights = vec![2, 0];
let mut dist = WeightedTreeIndex::new(&weights).unwrap();
dist.push(1).unwrap();
dist.update(1, 1).unwrap();
let mut rng = thread_rng();
let mut samples = [0; 3];
for _ in 0..100 {
// 50% chance to print 'a', 25% chance to print 'b', 25% chance to print 'c'
let i = dist.sample(&mut rng);
samples[i] += 1;
}
println!("Results: {:?}", choices.iter().zip(samples.iter()).collect::<Vec<_>>());
```

## Implementations§

source§### impl<W: Clone + PartialEq + PartialOrd + SampleUniform + SubAssign<W> + Weight> WeightedTreeIndex<W>

### impl<W: Clone + PartialEq + PartialOrd + SampleUniform + SubAssign<W> + Weight> WeightedTreeIndex<W>

source#### pub fn new<I>(weights: I) -> Result<Self, WeightError>

#### pub fn new<I>(weights: I) -> Result<Self, WeightError>

Creates a new `WeightedTreeIndex`

from a slice of weights.

Error cases:

`WeightError::InvalidWeight`

when a weight is not-a-number or negative.`WeightError::Overflow`

when the sum of all weights overflows.

source#### pub fn is_valid(&self) -> bool

#### pub fn is_valid(&self) -> bool

Returns `true`

if we can sample.

This is the case if the total weight of the tree is greater than zero.

source#### pub fn pop(&mut self) -> Option<W>

#### pub fn pop(&mut self) -> Option<W>

Removes the last weight and returns it, or `None`

if it is empty.

source#### pub fn push(&mut self, weight: W) -> Result<(), WeightError>

#### pub fn push(&mut self, weight: W) -> Result<(), WeightError>

Appends a new weight at the end.

Error cases:

`WeightError::InvalidWeight`

when a weight is not-a-number or negative.`WeightError::Overflow`

when the sum of all weights overflows.

source#### pub fn update(&mut self, index: usize, weight: W) -> Result<(), WeightError>

#### pub fn update(&mut self, index: usize, weight: W) -> Result<(), WeightError>

Updates the weight at an index.

Error cases:

`WeightError::InvalidWeight`

when a weight is not-a-number or negative.`WeightError::Overflow`

when the sum of all weights overflows.

source§### impl<W: Clone + PartialEq + PartialOrd + SampleUniform + SubAssign<W> + Weight> WeightedTreeIndex<W>

### impl<W: Clone + PartialEq + PartialOrd + SampleUniform + SubAssign<W> + Weight> WeightedTreeIndex<W>

source#### pub fn try_sample<R: Rng + ?Sized>(
&self,
rng: &mut R
) -> Result<usize, WeightError>

#### pub fn try_sample<R: Rng + ?Sized>( &self, rng: &mut R ) -> Result<usize, WeightError>

Samples a randomly selected index from the weighted distribution.

Returns an error if there are no elements or all weights are zero. This
is unlike `Distribution::sample`

, which panics in those cases.

## Trait Implementations§

source§### impl<W: Clone + Clone + PartialEq + PartialOrd + SampleUniform + SubAssign<W> + Weight> Clone for WeightedTreeIndex<W>

### impl<W: Clone + Clone + PartialEq + PartialOrd + SampleUniform + SubAssign<W> + Weight> Clone for WeightedTreeIndex<W>

source§#### fn clone(&self) -> WeightedTreeIndex<W>

#### fn clone(&self) -> WeightedTreeIndex<W>

1.0.0 · source§#### fn clone_from(&mut self, source: &Self)

#### fn clone_from(&mut self, source: &Self)

`source`

. Read moresource§### impl<W: Debug + Clone + PartialEq + PartialOrd + SampleUniform + SubAssign<W> + Weight> Debug for WeightedTreeIndex<W>

### impl<W: Debug + Clone + PartialEq + PartialOrd + SampleUniform + SubAssign<W> + Weight> Debug for WeightedTreeIndex<W>

source§### impl<W: Default + Clone + PartialEq + PartialOrd + SampleUniform + SubAssign<W> + Weight> Default for WeightedTreeIndex<W>

### impl<W: Default + Clone + PartialEq + PartialOrd + SampleUniform + SubAssign<W> + Weight> Default for WeightedTreeIndex<W>

source§#### fn default() -> WeightedTreeIndex<W>

#### fn default() -> WeightedTreeIndex<W>

source§### impl<'de, W> Deserialize<'de> for WeightedTreeIndex<W>where
W: Deserialize<'de> + Clone + PartialEq + PartialOrd + SampleUniform + SubAssign<W> + Weight,
W::Sampler: Deserialize<'de>,

### impl<'de, W> Deserialize<'de> for WeightedTreeIndex<W>where
W: Deserialize<'de> + Clone + PartialEq + PartialOrd + SampleUniform + SubAssign<W> + Weight,
W::Sampler: Deserialize<'de>,

source§#### fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,

#### fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,

source§### impl<W: Clone + PartialEq + PartialOrd + SampleUniform + SubAssign<W> + Weight> Distribution<usize> for WeightedTreeIndex<W>

### impl<W: Clone + PartialEq + PartialOrd + SampleUniform + SubAssign<W> + Weight> Distribution<usize> for WeightedTreeIndex<W>

Samples a randomly selected index from the weighted distribution.

Caution: This method panics if there are no elements or all weights are zero. However,
it is guaranteed that this method will not panic if a call to `WeightedTreeIndex::is_valid`

returns `true`

.

source§### impl<W: PartialEq + Clone + PartialEq + PartialOrd + SampleUniform + SubAssign<W> + Weight> PartialEq for WeightedTreeIndex<W>

### impl<W: PartialEq + Clone + PartialEq + PartialOrd + SampleUniform + SubAssign<W> + Weight> PartialEq for WeightedTreeIndex<W>

source§#### fn eq(&self, other: &WeightedTreeIndex<W>) -> bool

#### fn eq(&self, other: &WeightedTreeIndex<W>) -> bool

`self`

and `other`

values to be equal, and is used
by `==`

.