Home > Article > Web Front-end > How to Generate Weighted Random Numbers: Is Cumulative Probability Distribution the Answer?
Generate Weighted Random Number: Beyond Rejection Sampling
In the realm of probability, the generation of weighted random numbers serves as an essential tool for simulations and statistical modeling. While rejection sampling often serves as a straightforward solution, it presents limitations in performance and memory consumption.
An elegant alternative emerges in the form of cumulative probability distribution. This approach eliminates the need for a pre-constructed lookup table, leading to significant memory savings and constant-time performance in selecting values. Here's how it works in JavaScript:
function weightedRand(spec) { var sum = 0; for (var i in spec) { sum += spec[i]; } var r = Math.random() * sum; for (i in spec) { r -= spec[i]; if (r <= 0) return i; } }
Weighted random number generators often find applications in scenarios such as:
In specific cases, where the weights are evenly distributed, an even simpler approach proves effective: simply pick a random index from an array representing the possible values. However, this method falls short for uneven weight distributions.
Remember, the choice of implementation depends on factors such as the number of options, distribution of weights, and desired performance characteristics.
The above is the detailed content of How to Generate Weighted Random Numbers: Is Cumulative Probability Distribution the Answer?. For more information, please follow other related articles on the PHP Chinese website!