Skip to content

knotkit/prng

Generates seeded pseudorandom numbers and unbiased integers for reproducible simulations and tests

import {
function splitmix32(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

https://github.com/skeeto/hash-prospector hash-prospector

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

https://dl.acm.org/doi/10.1145/2660193.2660195 Fast Splittable Pseudorandom Number Generators

.

This generator is not cryptographically secure. Use crypto.getRandomValues() when unpredictability matters.

@param ― seed - Initial seed, coerced to a signed 32-bit integer.

@returns ― A stateful function that returns the next value in the range [0, 1).

splitmix32
,
function uniformInt(random: RandomSource, upperExclusive: number): number

Draw an integer uniformly from 0..upperExclusive - 1.

Multiplying a source value by 2^32 produces one unsigned 32-bit draw. When the requested range does not divide 2^32 evenly, a direct remainder would make its lowest outcomes slightly more likely. Rejection sampling discards the incomplete high end of the 32-bit range before taking the remainder, so every returned integer has exactly the same number of source draws mapping to it.

The source can be seeded or otherwise injected by the caller. Each value is validated at the point it is consumed because a stateful source can become invalid after earlier valid draws.

Consumes one source draw in the common case. The rejection region is always smaller than upperExclusive, so fewer than half of all draws are rejected and the expected number of draws is below two.

@param ― random - Function returning values in [0, 1).

@param ― upperExclusive - Exclusive upper bound, from 1 through 2^32.

@throws ― {PrngInvalidInputError} With code INVALID_BOUND when the bound is not an integer in 1..2^32, or INVALID_SOURCE_VALUE when the source returns a value outside [0, 1).

uniformInt
} from 'knotkit/prng'
const
const random: () => number
random
=
function splitmix32(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

https://github.com/skeeto/hash-prospector hash-prospector

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

https://dl.acm.org/doi/10.1145/2660193.2660195 Fast Splittable Pseudorandom Number Generators

.

This generator is not cryptographically secure. Use crypto.getRandomValues() when unpredictability matters.

@param ― seed - Initial seed, coerced to a signed 32-bit integer.

@returns ― A stateful function that returns the next value in the range [0, 1).

splitmix32
(42)
const random: () => number
random
() // 0.12848330102860928
const random: () => number
random
() // 0.03353364090435207
function uniformInt(random: RandomSource, upperExclusive: number): number

Draw an integer uniformly from 0..upperExclusive - 1.

Multiplying a source value by 2^32 produces one unsigned 32-bit draw. When the requested range does not divide 2^32 evenly, a direct remainder would make its lowest outcomes slightly more likely. Rejection sampling discards the incomplete high end of the 32-bit range before taking the remainder, so every returned integer has exactly the same number of source draws mapping to it.

The source can be seeded or otherwise injected by the caller. Each value is validated at the point it is consumed because a stateful source can become invalid after earlier valid draws.

Consumes one source draw in the common case. The rejection region is always smaller than upperExclusive, so fewer than half of all draws are rejected and the expected number of draws is below two.

@param ― random - Function returning values in [0, 1).

@param ― upperExclusive - Exclusive upper bound, from 1 through 2^32.

@throws ― {PrngInvalidInputError} With code INVALID_BOUND when the bound is not an integer in 1..2^32, or INVALID_SOURCE_VALUE when the source returns a value outside [0, 1).

uniformInt
(
const random: () => number
random
, 6) + 1 // a fair die roll
prng.ts
import {
function uniformInt64(random: RandomSource64, upperExclusive: bigint): bigint

Draw an integer uniformly from 0..upperExclusive - 1.

This is the 64-bit counterpart of uniformInt. It consumes a source that already returns unsigned 64-bit draws, so no floating-point step stands between the generator and the sample, and bounds above 2^32 stay exact.

When the requested range does not divide 2^64 evenly, a direct remainder would make its lowest outcomes slightly more likely. Rejection sampling discards the incomplete high end of the 64-bit range before taking the remainder, so every returned integer has exactly the same number of source draws mapping to it.

The source can be seeded or otherwise injected by the caller. Each value is validated at the point it is consumed because a stateful source can become invalid after earlier valid draws.

Consumes one source draw in the common case. The rejection region is always smaller than upperExclusive, so fewer than half of all draws are rejected and the expected number of draws is below two.

@param ― random - Function returning unsigned 64-bit values in [0, 2^64).

@param ― upperExclusive - Exclusive upper bound, from 1 through 2^64.

@throws ― {PrngInvalidInputError} With code INVALID_BOUND when the bound is not a bigint in 1..2^64, or INVALID_SOURCE_VALUE when the source returns a value outside [0, 2^64).

uniformInt64
,
function xoroshiro128StarStar(initialState: Xoroshiro128StarStarState): Xoroshiro128StarStar

Create a xoroshiro128** 1.0 pseudorandom number generator.

The two input words are reduced modulo 2^64. They must not both reduce to zero because the all-zero state is fixed and would only emit zeroes. Each call to next() runs in constant time, mutates the private 128-bit state, and returns the same unsigned 64-bit value as the reference C implementation.

jump() advances by 2^64 outputs and longJump() advances by 2^96 outputs. Both run in constant space and a fixed 128 state transitions.

This generator is not cryptographically secure. Use crypto.getRandomValues() when unpredictability matters.

@param ― initialState - Two integers representing the initial 64-bit state words.

@returns ― A generator with private state and fixed-distance jump operations.

@throws ― {PrngInvalidInputError} With code INVALID_STATE when the state does not contain two bigints or both words reduce to zero modulo 2^64.

xoroshiro128StarStar
} from 'knotkit/prng'
const
const random: Xoroshiro128StarStar
random
=
function xoroshiro128StarStar(initialState: Xoroshiro128StarStarState): Xoroshiro128StarStar

Create a xoroshiro128** 1.0 pseudorandom number generator.

The two input words are reduced modulo 2^64. They must not both reduce to zero because the all-zero state is fixed and would only emit zeroes. Each call to next() runs in constant time, mutates the private 128-bit state, and returns the same unsigned 64-bit value as the reference C implementation.

jump() advances by 2^64 outputs and longJump() advances by 2^96 outputs. Both run in constant space and a fixed 128 state transitions.

This generator is not cryptographically secure. Use crypto.getRandomValues() when unpredictability matters.

@param ― initialState - Two integers representing the initial 64-bit state words.

@returns ― A generator with private state and fixed-distance jump operations.

@throws ― {PrngInvalidInputError} With code INVALID_STATE when the state does not contain two bigints or both words reduce to zero modulo 2^64.

xoroshiro128StarStar
([1n, 2n])
const random: Xoroshiro128StarStar
random
.
Xoroshiro128StarStar.next: () => bigint

Advance the state once and return an unsigned 64-bit value.

next
() // 0x1680n
const random: Xoroshiro128StarStar
random
.
Xoroshiro128StarStar.next: () => bigint

Advance the state once and return an unsigned 64-bit value.

next
() // 0x16c3804380n
function uniformInt64(random: RandomSource64, upperExclusive: bigint): bigint

Draw an integer uniformly from 0..upperExclusive - 1.

This is the 64-bit counterpart of uniformInt. It consumes a source that already returns unsigned 64-bit draws, so no floating-point step stands between the generator and the sample, and bounds above 2^32 stay exact.

When the requested range does not divide 2^64 evenly, a direct remainder would make its lowest outcomes slightly more likely. Rejection sampling discards the incomplete high end of the 64-bit range before taking the remainder, so every returned integer has exactly the same number of source draws mapping to it.

The source can be seeded or otherwise injected by the caller. Each value is validated at the point it is consumed because a stateful source can become invalid after earlier valid draws.

Consumes one source draw in the common case. The rejection region is always smaller than upperExclusive, so fewer than half of all draws are rejected and the expected number of draws is below two.

@param ― random - Function returning unsigned 64-bit values in [0, 2^64).

@param ― upperExclusive - Exclusive upper bound, from 1 through 2^64.

@throws ― {PrngInvalidInputError} With code INVALID_BOUND when the bound is not a bigint in 1..2^64, or INVALID_SOURCE_VALUE when the source returns a value outside [0, 2^64).

uniformInt64
(
const random: Xoroshiro128StarStar
random
.
Xoroshiro128StarStar.next: () => bigint

Advance the state once and return an unsigned 64-bit value.

next
, 6n) + 1n // a fair die roll as a bigint
  • replay the same random sequence from a seed in tests, simulations, or procedural generation
  • roll an unbiased integer in 1..n without modulo bias
  • draw unsigned 64-bit values larger than 2^53 without losing precision or capping the bound
  • give parallel workers non-overlapping subsequences of one sequence
  • produce the same random values in a browser, in Node.js, and in Bun
{"v":1,"box":[59.0243,94.1597,845.1333,437.3555],"x":{"s":"linear","lim":[0.339,6.661],"inv":false,"g":0,"t":"Die face","tk":[[1,"1"],[2,"2"],[3,"3"],[4,"4"],[5,"5"],[6,"6"]]},"y":{"s":"linear","lim":[-72.1687836487,72.1687836487],"inv":false,"g":0,"tk":[[-57.735026919,"−58"],[0,"0"],[57.735026919,"+58"]]},"ti":"Replaying a seed repeats every count; 12 of 12 counts lie within 2 SD of 1,000","a":[{"k":"scatter","c":"#1d5fa6","s":"xy","d":[0.92,38,1.92,-8,2.92,-38,3.92,16,4.92,-1,5.92,-7],"p":[131.27,175.4,255.61,284.78,379.96,356.11,504.3,227.71,628.65,268.14,752.99,282.4],"r":4.96},{"k":"scatter","c":"#c4501b","s":"xy","d":[1.08,20,2.08,34,3.08,-32,4.08,12,5.08,11,6.08,-45],"p":[151.16,218.2,275.51,184.91,399.85,341.84,524.2,237.22,648.54,239.6,772.89,372.76],"r":4.96},{"k":"segments","c":"#8c8c84"},{"k":"segments","c":"#8c8c84"},{"k":"fill","c":"#5b6b7c"},{"k":"annotation","c":"#5c5c57"},{"k":"annotation","c":"#1d5fa6"},{"k":"annotation","c":"#c4501b"},{"k":"annotation","c":"#5b6b7c"}],"lg":[]} 1 2 3 4 5 6 Die face −58 0 +58 Rolls minus the expected 1,000 seed 42, run twice seed 43 ±2 SD of a fair die Replaying a seed repeats every count; 12 of 12 counts lie within 2 SD of 1,000
{"v":1,"box":[59.0243,122.3921,397.1333,437.3555],"x":{"s":"linear","lim":[0.339,6.661],"inv":false,"g":0,"t":"Die face","tk":[[1,"1"],[2,"2"],[3,"3"],[4,"4"],[5,"5"],[6,"6"]]},"y":{"s":"linear","lim":[-72.1687836487,72.1687836487],"inv":false,"g":0,"tk":[[-57.735026919,"−58"],[0,"0"],[57.735026919,"+58"]]},"ti":"Replaying a seed repeats every count; 12\nof 12 counts lie within 2 SD of 1,000","a":[{"k":"scatter","c":"#1d5fa6","s":"xy","d":[0.92,38,1.92,-8,2.92,-38,3.92,16,4.92,-1,5.92,-7],"p":[90.1,196.95,143.58,297.33,197.06,362.79,250.54,244.96,304.02,282.06,357.5,295.15],"r":4.96},{"k":"scatter","c":"#c4501b","s":"xy","d":[1.08,20,2.08,34,3.08,-32,4.08,12,5.08,11,6.08,-45],"p":[98.65,236.23,152.14,205.68,205.62,349.7,259.1,253.69,312.58,255.87,366.06,378.07],"r":4.96},{"k":"segments","c":"#8c8c84"},{"k":"segments","c":"#8c8c84"},{"k":"fill","c":"#5b6b7c"},{"k":"annotation","c":"#5c5c57"},{"k":"annotation","c":"#1d5fa6"},{"k":"annotation","c":"#c4501b"},{"k":"annotation","c":"#5b6b7c"}],"lg":[]} 1 2 3 4 5 6 Die face −58 0 +58 Rolls minus the expected 1,000 seed 42, run twice seed 43 ±2 SD of a fair die Replaying a seed repeats every count; 12 of 12 counts lie within 2 SD of 1,000
  • SplitMix32, seed 42: 6,000 six-sided die rolls.
  • Counts for faces 1 to 6: 1038, 992, 962, 1016, 999, 993. Expectation: 1000 each.
  • Replaying seed 42 reproduced every count. Counts for seed 43: 1020, 1034, 968, 1012, 1011, 955.

Hover or focus a chart for exact values. Each change reruns demo.ts against knotkit/prng in your browser; the defaults reproduce the README figure.

ExportReturnsDoes
splitmix32RandomSourceSeeded 32-bit generator; the seed is coerced to a signed 32-bit integer and each call yields a value in `[0, 1)`.
xoroshiro128StarStarXoroshiro128StarStarSeeded 128-bit-state generator over unsigned 64-bit `bigint` draws, matching xoroshiro128** 1.0; input words are reduced modulo 2^64 and must not both reduce to zero.
uniformIntnumberUnbiased integer in `0..upperExclusive - 1` from an injected `RandomSource`; holds no state but advances the source once per consumed draw, rejected draws included.
uniformInt64bigintUnbiased `bigint` in `0..upperExclusive - 1` from an injected `RandomSource64`, with no floating-point step, so bounds above 2^32 stay exact.

Cost per member. Open a row for every operation.

splitmix32 1 members
MemberCost
drawO(1)
xoroshiro128StarStar 4 members
MemberCost
kindO(1)
nextO(1)
jump128 state transitions
longJump128 state transitions

Every error this module throws is PrngInvalidInputError, with a code from a closed, exported list. Branch on the code; the message is for people.

INVALID_BOUND INVALID_SOURCE_VALUE INVALID_STATE
If you need to…Use instead
generate tokens, passwords, keys, or nonces an attacker cannot predictuniku
one throwaway random number with no reproducibility requirementthe platform Math.random function
shuffle an array or pick a weighted choiceknotkit/sampling
derive a fingerprint or a shard key from bytes or textknotkit/hash
draw from a named distributionknotkit/distribution
test whether draws fit a distributionknotkit/hypothesis-test

Measured by the suite in packages/prng/__tests__/bench. The numbers come from one machine, so run the suite on yours before deciding on speed alone.

Prompt · knotkit/prng
Use knotkit/prng for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/prng'.

Exports:
- `splitmix32` → `RandomSource`: Seeded 32-bit generator; the seed is coerced to a signed 32-bit integer and each call yields a value in `[0, 1)`.
- `xoroshiro128StarStar` → `Xoroshiro128StarStar`: Seeded 128-bit-state generator over unsigned 64-bit `bigint` draws, matching xoroshiro128** 1.0; input words are reduced modulo 2^64 and must not both reduce to zero.
- `uniformInt` → `number`: Unbiased integer in `0..upperExclusive - 1` from an injected `RandomSource`; holds no state but advances the source once per consumed draw, rejected draws included.
- `uniformInt64` → `bigint`: Unbiased `bigint` in `0..upperExclusive - 1` from an injected `RandomSource64`, with no floating-point step, so bounds above 2^32 stay exact.

Use something else when:
- generate tokens, passwords, keys, or nonces an attacker cannot predict → uniku (https://www.npmjs.com/package/uniku)
- one throwaway random number with no reproducibility requirement → the platform Math.random function
- shuffle an array or pick a weighted choice → knotkit/sampling
- derive a fingerprint or a shard key from bytes or text → knotkit/hash
- draw from a named distribution → knotkit/distribution
- test whether draws fit a distribution → knotkit/hypothesis-test

Errors are PrngInvalidInputError with a `code` property. Branch on `error.code`, never on the message.

Full page: https://knotkit.jkomyno.dev/modules/prng.md
Types: node_modules/knotkit/prng/ and https://knotkit.jkomyno.dev/reference/knotkit/prng/