Creates a deterministic 32-bit pseudorandom number generator.
Each call advances a private state by 0x9e3779b9. This constant equals
floor(2^32 / phi), where phi is the golden ratio. Addition wraps modulo
2^32. Because the increment is odd, it is coprime to 2^32. The resulting
Weyl sequence visits every 32-bit state once before it repeats.
The mixing function uses the constants 0x21f0aaad and 0x735a2d97 from
the
search
for low avalanche bias. Its XOR-shifts and multiplications by odd integers
are invertible over 32-bit values. The mixer therefore preserves the full
period while diffusing nearby states across the output bits.
Math.imul and the bitwise operators keep the mixing steps in 32-bit
arithmetic. The final unsigned conversion produces an integer from 0 to
2^32 - 1. Dividing by 2^32 maps that integer to [0, 1).
The SplitMix family was introduced by Steele, Lea, and Flood in
Sample a uniform subset of 0..populationSize - 1 in ascending order.
Floyd's algorithm uses O(sampleSize) expected auxiliary space, followed by
an O(sampleSize log sampleSize) canonical sort. The inputs are not mutated.
@throws ― {SamplingInvalidInputError} With code INVALID_POPULATION_SIZE when
populationSize is not a safe integer in 0..2^32, or
INVALID_SAMPLE_SIZE when sampleSize is not representable or exceeds the
population.
@throws ― {PrngInvalidInputError} With code INVALID_SOURCE_VALUE when the
random source returns a value outside [0, 1).
Sample one index proportionally to its finite non-negative weight.
Runs in O(weights.length) time and O(1) auxiliary space. Scaling by the
largest weight keeps the cumulative sum finite without changing the
distribution. The weights are not mutated.
@throws ― {SamplingInvalidInputError} With code INVALID_WEIGHT when a weight
is negative or non-finite, or ZERO_TOTAL_WEIGHT when the array is empty or
contains no positive weight.
@throws ― {PrngInvalidInputError} With code INVALID_SOURCE_VALUE when the
random source returns a value outside [0, 1).
weightedChoice } from'knotkit/sampling'
const
constrandom: () =>number
random=
functionsplitmix32(seed:number): () =>number
Creates a deterministic 32-bit pseudorandom number generator.
Each call advances a private state by 0x9e3779b9. This constant equals
floor(2^32 / phi), where phi is the golden ratio. Addition wraps modulo
2^32. Because the increment is odd, it is coprime to 2^32. The resulting
Weyl sequence visits every 32-bit state once before it repeats.
The mixing function uses the constants 0x21f0aaad and 0x735a2d97 from
the
search
for low avalanche bias. Its XOR-shifts and multiplications by odd integers
are invertible over 32-bit values. The mixer therefore preserves the full
period while diffusing nearby states across the output bits.
Math.imul and the bitwise operators keep the mixing steps in 32-bit
arithmetic. The final unsigned conversion produces an integer from 0 to
2^32 - 1. Dividing by 2^32 maps that integer to [0, 1).
The SplitMix family was introduced by Steele, Lea, and Flood in
Sample a uniform subset of 0..populationSize - 1 in ascending order.
Floyd's algorithm uses O(sampleSize) expected auxiliary space, followed by
an O(sampleSize log sampleSize) canonical sort. The inputs are not mutated.
@throws ― {SamplingInvalidInputError} With code INVALID_POPULATION_SIZE when
populationSize is not a safe integer in 0..2^32, or
INVALID_SAMPLE_SIZE when sampleSize is not representable or exceeds the
population.
@throws ― {PrngInvalidInputError} With code INVALID_SOURCE_VALUE when the
random source returns a value outside [0, 1).
sampleIndices(
constrandom: () =>number
random, 10, 3) // three distinct indices in ascending order
Sample one index proportionally to its finite non-negative weight.
Runs in O(weights.length) time and O(1) auxiliary space. Scaling by the
largest weight keeps the cumulative sum finite without changing the
distribution. The weights are not mutated.
@throws ― {SamplingInvalidInputError} With code INVALID_WEIGHT when a weight
is negative or non-finite, or ZERO_TOTAL_WEIGHT when the array is empty or
contains no positive weight.
@throws ― {PrngInvalidInputError} With code INVALID_SOURCE_VALUE when the
random source returns a value outside [0, 1).
weightedChoice(
constrandom: () =>number
random, [1, 2, 0]) // index 0 or 1; never 2
sampling.ts●
import {
functionsplitmix32(seed:number): () =>number
Creates a deterministic 32-bit pseudorandom number generator.
Each call advances a private state by 0x9e3779b9. This constant equals
floor(2^32 / phi), where phi is the golden ratio. Addition wraps modulo
2^32. Because the increment is odd, it is coprime to 2^32. The resulting
Weyl sequence visits every 32-bit state once before it repeats.
The mixing function uses the constants 0x21f0aaad and 0x735a2d97 from
the
search
for low avalanche bias. Its XOR-shifts and multiplications by odd integers
are invertible over 32-bit values. The mixer therefore preserves the full
period while diffusing nearby states across the output bits.
Math.imul and the bitwise operators keep the mixing steps in 32-bit
arithmetic. The final unsigned conversion produces an integer from 0 to
2^32 - 1. Dividing by 2^32 maps that integer to [0, 1).
The SplitMix family was introduced by Steele, Lea, and Flood in
Create a uniform reservoir sampler over a stream of unknown length.
Vitter's Algorithm R: the first capacity values fill the reservoir, and the
n-th value after that replaces a uniformly drawn slot with probability
capacity / n. One draw per value past the reservoir keeps every observed
value at inclusion probability capacity / n after each one.
The sampler accepts at most 2^32 values, the same population bound
sampleIndices accepts, because the slot draw for the n-th value asks
uniformInt for a bound of n.
Replaying the same values against the same source state reproduces every
replacement and every snapshot.
@param ― random - Function returning values in [0, 1).
@param ― capacity - The maximum number of retained values, from 0 through
2^32 - 1.
@throws ― {SamplingInvalidInputError} With code INVALID_CAPACITY when
capacity is not a safe integer in 0..2^32 - 1. Validation happens before
the source is ever called.
Create a uniform reservoir sampler over a stream of unknown length.
Vitter's Algorithm R: the first capacity values fill the reservoir, and the
n-th value after that replaces a uniformly drawn slot with probability
capacity / n. One draw per value past the reservoir keeps every observed
value at inclusion probability capacity / n after each one.
The sampler accepts at most 2^32 values, the same population bound
sampleIndices accepts, because the slot draw for the n-th value asks
uniformInt for a bound of n.
Replaying the same values against the same source state reproduces every
replacement and every snapshot.
@param ― random - Function returning values in [0, 1).
@param ― capacity - The maximum number of retained values, from 0 through
2^32 - 1.
@throws ― {SamplingInvalidInputError} With code INVALID_CAPACITY when
capacity is not a safe integer in 0..2^32 - 1. Validation happens before
the source is ever called.
reservoirSampler<number>(
functionsplitmix32(seed:number): () =>number
Creates a deterministic 32-bit pseudorandom number generator.
Each call advances a private state by 0x9e3779b9. This constant equals
floor(2^32 / phi), where phi is the golden ratio. Addition wraps modulo
2^32. Because the increment is odd, it is coprime to 2^32. The resulting
Weyl sequence visits every 32-bit state once before it repeats.
The mixing function uses the constants 0x21f0aaad and 0x735a2d97 from
the
search
for low avalanche bias. Its XOR-shifts and multiplications by odd integers
are invertible over 32-bit values. The mixer therefore preserves the full
period while diffusing nearby states across the output bits.
Math.imul and the bitwise operators keep the mixing steps in 32-bit
arithmetic. The final unsigned conversion produces an integer from 0 to
2^32 - 1. Dividing by 2^32 maps that integer to [0, 1).
The SplitMix family was introduced by Steele, Lea, and Flood in
A fresh copy of the retained values in slot order. O(capacity).
Slot order is deterministic under replay, but it is neither stream order
nor a uniformly random order; pass the result through shuffled when a
random order matters. Values are held by reference and never cloned.
Consumes no draw and leaves the sampler unchanged, and mutating the
returned array does not affect it.
snapshot() // three of the five values, each retained with probability 3/5
4,000 weighted choices with seed 42 and weights [1, 2, 7, 0].
Observed picks per item: 397, 828, 2775, 0.
The zero-weight item is ineligible. Each call draws one item independently.
Hover or focus a chart for exact values. Each change reruns demo.ts against knotkit/sampling in your browser; the defaults reproduce the README figure.
Two ascending indices whose gap lies inside the requested inclusive interval, each valid pair equally likely; one draw plus a binary search over the pair rank.
One index placed across cumulative intervals proportional to the weights, scaled by the largest weight so the sum stays finite; O(n) time and O(1) space.
k indices without replacement by Efraimidis-Spirakis logarithmic keys in a bounded min queue, one draw per eligible entry, ties to the lower index; O(n log k) time and O(k) space.
The same k indices without replacement taken from log-weights directly, skipping `Math.exp`, so a log-weight of `-800` stays eligible and `-Infinity` marks an entry as unreachable; O(n log k) time and O(k) space.
Vitter's Algorithm R over a stream: fills the first `capacity` values, then retains the n-th with probability `capacity / n`. `add` throws `STREAM_LIMIT_EXCEEDED` once 2^32 values have been observed.
Measured by the suite in packages/sampling/__tests__/bench. The numbers come from one machine, so run the suite on yours before deciding on speed alone.
Use knotkit/sampling for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/sampling'.
Exports:
- `sampleIndices` → `readonly number[]`: Floyd's uniform subset returned in ascending source order; O(k) expected plus O(k log k) to sort, with no population-sized allocation.
- `samplePair` → `readonly [number, number]`: Two distinct indices in ascending order, drawn as a two-item subset offset into the requested range; O(1) time and space.
- `sampleConstrainedPair` → `readonly [number, number]`: Two ascending indices whose gap lies inside the requested inclusive interval, each valid pair equally likely; one draw plus a binary search over the pair rank.
- `shuffled` → `readonly T[]`: Fisher-Yates permutation of a copy; O(n) time and O(n) space, and the input array is left untouched.
- `weightedChoice` → `number`: One index placed across cumulative intervals proportional to the weights, scaled by the largest weight so the sum stays finite; O(n) time and O(1) space.
- `weightedSample` → `readonly number[]`: k indices without replacement by Efraimidis-Spirakis logarithmic keys in a bounded min queue, one draw per eligible entry, ties to the lower index; O(n log k) time and O(k) space.
- `weightedSampleFromLogWeights` → `readonly number[]`: The same k indices without replacement taken from log-weights directly, skipping `Math.exp`, so a log-weight of `-800` stays eligible and `-Infinity` marks an entry as unreachable; O(n log k) time and O(k) space.
- `reservoirSampler` → `ReservoirSampler<T>`: Vitter's Algorithm R over a stream: fills the first `capacity` values, then retains the n-th with probability `capacity / n`. `add` throws `STREAM_LIMIT_EXCEEDED` once 2^32 values have been observed.
Inputs and their sources:
- randomness, consumed once per draw and never created or owned; the same source state replays the same sample: `RandomSource` from `knotkit/prng`
Use something else when:
- a seeded random source of your own, or the sequence the draws come from → knotkit/prng
- randomness an attacker must not be able to predict → crypto.getRandomValues
- sample with replacement → one weighted draw per item over a shared random source
- keep the drawn items ordered, or evict the weakest of them as more arrive → knotkit/heap
- estimate how many distinct values a stream held, or how often one occurred → knotkit/scalar-sketch
- draw from a named distribution → knotkit/distribution
- test whether draws fit a distribution → knotkit/hypothesis-test
Errors are SamplingInvalidInputError with a `code` property. Branch on `error.code`, never on the message.
Full page: https://knotkit.jkomyno.dev/modules/sampling.md
Types: node_modules/knotkit/sampling/ and https://knotkit.jkomyno.dev/reference/knotkit/sampling/