Skip to content

weightedSampleFromLogWeights(random, logWeights, sampleSize): readonly number[]

Defined in: packages/sampling/src/weighted-sample-from-log-weights.ts:30

Sample indices without replacement from log-weights, in ascending source order.

Each entry is the natural logarithm of a non-negative weight, so weightedSampleFromLogWeights(random, weights.map(Math.log), sampleSize) returns exactly what weightedSample returns for the same finite weights and source state. Skipping the round trip through Math.exp keeps an entry eligible and separable however small its weight is: a log-weight of -800 is a valid input even though Math.exp(-800) is zero.

-Infinity marks an ineligible entry, mirroring a zero weight exactly: it is skipped before its draw and can never be returned. Every other eligible entry consumes exactly one draw, in source order, and a sampleSize of zero consumes none. Uses Efraimidis-Spirakis keys and a bounded min priority queue, taking O(logWeights.length log sampleSize) time and O(sampleSize) auxiliary space. Equal keys prefer the lower source index, and the log-weights are not mutated.

RandomSource

readonly number[]

number

readonly number[]

With code INVALID_LOG_WEIGHT when a log-weight is NaN or +Infinity, INVALID_SAMPLE_SIZE when sampleSize is not a valid array size, or INSUFFICIENT_POSITIVE_WEIGHT when too few log-weights are finite.

With code INVALID_SOURCE_VALUE when the random source returns a value outside [0, 1).