# knotkit/prng

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

## Use

```ts
import { splitmix32, uniformInt } from 'knotkit/prng'

const random = splitmix32(42)

random() // 0.12848330102860928
random() // 0.03353364090435207
uniformInt(random, 6) + 1 // a fair die roll
```

```ts
import { uniformInt64, xoroshiro128StarStar } from 'knotkit/prng'

const random = xoroshiro128StarStar([1n, 2n])

random.next() // 0x1680n
random.next() // 0x16c3804380n
uniformInt64(random.next, 6n) + 1n // a fair die roll as a bigint
```

## What it solves

* 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

## Try it

Seed4242Rolls6,0006000Reset

* 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`](https://github.com/jkomyno/knotkit/blob/main/packages/prng/demo.ts) against `knotkit/prng` in your browser; the defaults reproduce the README figure.

## API

| Export                                                                            | Returns                | Does                                                                                                                                                                       |
| --------------------------------------------------------------------------------- | ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`splitmix32`](/reference/knotkit/prng/functions/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`](/reference/knotkit/prng/functions/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`](/reference/knotkit/prng/functions/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`](/reference/knotkit/prng/functions/uniformint64/)                 | `bigint`               | Unbiased \`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

| Member | Cost |
| ------ | ---- |
| `draw` | O(1) |

`xoroshiro128StarStar` 4 members

| Member     | Cost                  |
| ---------- | --------------------- |
| `kind`     | O(1)                  |
| `next`     | O(1)                  |
| `jump`     | 128 state transitions |
| `longJump` | 128 state transitions |

## Errors

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`

## When not to use it

| If you need to…                                                        | Use instead                                            |
| ---------------------------------------------------------------------- | ------------------------------------------------------ |
| 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`](/modules/sampling/)               |
| derive a fingerprint or a shard key from bytes or text                 | [`knotkit/hash`](/modules/hash/)                       |
| draw from a named distribution                                         | [`knotkit/distribution`](/modules/distribution/)       |
| test whether draws fit a distribution                                  | [`knotkit/hypothesis-test`](/modules/hypothesis-test/) |

## Performance

Measured by the suite in [`packages/prng/__tests__/bench`](https://github.com/jkomyno/knotkit/tree/main/packages/prng/__tests__/bench). The numbers come from one machine, so run the suite on yours before deciding on speed alone.

## Prompt an agent

Prompt · knotkit/prngCopy prompt

```
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/
```

## See also

* [API reference](/reference/knotkit/prng/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/prng/knotkit.capability.json)this page as JSON, also in the installed package
* [Edit this page on GitHub](https://github.com/jkomyno/knotkit/edit/main/packages/prng/knotkit.capability.json)suggest a change to the source record
