Home >Backend Development >C++ >How Can Boost's Random Number Generator Be Used for Weighted Random Number Selection?

How Can Boost's Random Number Generator Be Used for Weighted Random Number Selection?

Linda Hamilton
Linda HamiltonOriginal
2024-12-15 20:43:13494browse

How Can Boost's Random Number Generator Be Used for Weighted Random Number Selection?

Weighted Random Number Generation

Choosing random numbers with specific probabilities is a common task in programming. Boost's random number generator provides a convenient way to select items with weighted probabilities.

Consider the scenario where you want to pick a random number between 1 and 3 with the following weights:

  • 1: 90%
  • 2: 56%
  • 3: 4%

Algorithm

Boost does not have built-in functionality for weighted random number generation. However, there is a simple algorithm that can be applied:

  1. Calculate the Total Weight: Sum the weights of all items.
  2. Generate a Random Number: Choose a random number between 0 and the total weight.
  3. Iterate Through Weights: Go through each item's weight, subtracting it from the random number until the number becomes less than the current item's weight.
  4. Return Item: The item corresponding to the position where the random number became negative is the chosen item.

Code Example

In Boost, using the random_device and mt19937 random number generator:

std::mt19937 rng(std::random_device{}());
int total_weight = 90 + 56 + 4;
for (int i = 0; i < total_weight; i++) {
    int random_number = rng() % total_weight;
    int current_weight = 90;
    if (random_number < current_weight) {
        return 1;
    }
    current_weight += 56;
    if (random_number < current_weight) {
        return 2;
    }
    return 3; // Reached the end of the weights
}

Optimizations

If weights rarely change and random picks are frequent, an optimization can be applied by storing the cumulative weight sum in each item. This allows for a more efficient binary search approach.

Additionally, if the number of items is unknown but the weights are known, reservoir sampling can be adapted for weighted random number generation.

The above is the detailed content of How Can Boost's Random Number Generator Be Used for Weighted Random Number Selection?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn