|
tgen
|
Sampler for repeated draws from a fixed weighted distribution. More...
Public Member Functions | |
| weighted_sampler (const std::vector< T > &distribution) | |
| Creates a weighted sampler from a probability distribution. | |
| size_t | next () const |
| Generates a random index with probability proportional to the distribution. | |
Sampler for repeated draws from a fixed weighted distribution.
Builds, in O(n) time, a structure that produces independent indices i in [0, n - 1] with probability proportional to distribution[i], in O(1) per draw.
Internally uses the alias method. The internal weight type is selected from the input type T:
If only a single index is needed, prefer tgen::next_by_distribution. To draw k indices in one call, prefer tgen::many_by_distribution. Use tgen::weighted_sampler directly when many independent draws from the same distribution are needed but they cannot all be generated at once (for example, when the next draw depends on previous draws).
|
inline |
Creates a weighted sampler from a probability distribution.
| T | Arithmetic type of the weights. |
| distribution | Non-negative weights. |
The probability of drawing index i is distribution[i] / sum(distribution).
| std::runtime_error | if distribution is invalid. |
O(|distribution|).
|
inline |
Generates a random index with probability proportional to the distribution.
Indices with weight 0 are never returned.
O(1).