Sampling with Cumulative Weights

Nonnegative weights can define consecutive intervals. Draw a uniform position in the total span and choose the interval covering it.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Map a discrete draw
  2. Check zero weight
  3. Assign a half-open range to each integer weight
  4. Validate weights and search for the first boundary above the draw

Map a discrete draw

Weights 2, 3, and 1 have cumulative ends 2, 5, and 6. For a uniform integer from 0 through 5, positions 0 and 1 select the first outcome, 2 to 4 select the second, and 5 selects the last. Prefix totals construct these ends.

Check zero weight

A zero creates an empty interval. Specify a strictly greater end boundary so that interval has no selected position. Monotone boundary search can locate the chosen end.[1]

Assign a half-open range to each integer weight

With positive weights two, five and three, a uniformly drawn integer from zero through nine can map to A for zero and one, B for two through six, and C for seven through nine. Every outcome receives as many positions as its weight. See half-open ranges.

A: [0,2) → 2 positions
B: [2,7) → 5 positions
C: [7,10) → 3 positions
Boundary tests: 1→A, 2→B, 6→B, 7→C

Validate weights and search for the first boundary above the draw

A zero weight contributes an empty interval and must never be returned. A collection with no positive total has no valid draw. Large static tables can search increasing cumulative ends using a strict comparison.

References

  1. Eric Lehman, F. Thomson Leighton and Albert R. Meyer, Mathematics for Computer Science ↩