Heim > Web-Frontend > js-Tutorial > Hauptteil

Wie kann die Generierung gewichteter Zufallszahlen effizienter gestaltet werden?

DDD
Freigeben: 2024-11-14 11:56:02
Original
450 Leute haben es durchsucht

How Can Weighted Random Number Generation Be Optimized for Efficiency?

Generate Weighted Random Numbers

Weighted random number generation involves selecting a random number from a range where the probability of each number is determined by a weight. This task arises in various applications, such as simulations and games.

Initial Solution

A common approach is rejection sampling, as exemplified in the provided ColdFusion code. This method involves creating a lookup table with elements distributed according to their weights. However, this approach has limitations, such as linear overhead in building the table and potential memory consumption issues.

Alternative Strategies

  • Linear Summing: Another strategy involves iteratively summing the weights until the sum exceeds a randomly generated number in the range [0,1). The associated value is then returned. This approach has no upfront costs but a linear time complexity.
  • Reservoir Sampling: This method involves selecting a random sample from a stream of elements. As each element is encountered, it is added to the reservoir with a probability proportional to its weight. The reservoir size remains fixed, ensuring a constant time complexity.
  • Alias Sampling: This technique utilizes a precomputed table to select random numbers from a weighted distribution. It guarantees a constant time complexity and is generally more efficient than the other approaches for large or highly skewed weight distributions.

Implementation

An implementation of weighted random number generation in JavaScript using alias sampling:

function weightedRand(weights) {
  // Build the alias table
  let table = [];
  let totalWeight = 0;
  for (let i = 0; i < weights.length; i++) {
    totalWeight += weights[i];
  }
  for (let i = 0; i < weights.length; i++) {
    let prob = weights[i] / totalWeight;
    let alias = i;
    table.push({ prob: prob, alias: alias });
  }
  
  // Generate a random number
  return function() {
    let r = Math.random() * totalWeight;
    let i = 0;
    let alias = -1;
    while (i < table.length && alias === -1) {
      if (r < table[i].prob) {
        alias = i;
      } else {
        r -= table[i].prob;
        i = table[i].alias;
      }
    }
    return alias;
  }
}
Nach dem Login kopieren

Das obige ist der detaillierte Inhalt vonWie kann die Generierung gewichteter Zufallszahlen effizienter gestaltet werden?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Quelle:php.cn
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage