Home > Web Front-end > JS Tutorial > How to Generate Weighted Random Numbers: Is Cumulative Probability Distribution the Answer?

How to Generate Weighted Random Numbers: Is Cumulative Probability Distribution the Answer?

Linda Hamilton
Release: 2024-11-11 04:09:03
Original
957 people have browsed it

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;
  }
}
Copy after login

Weighted random number generators often find applications in scenarios such as:

  • Simulation of probabilistic events
  • Selection of items from an inventory with varying probabilities
  • Generating realistic data sets that conform to non-uniform distributions

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template