Randomness utilities from a selection of elements.
$ npm install ml-random
This package is ESM-only. CommonJS consumers need Node.js ≥ 22.12 (or any 24.x or later) to require() it, or can migrate to import.
import { Random } from 'ml-random';
// Pass a seed for reproducible draws, a custom generator function, or nothing to use Math.random.
const random = new Random(42);
random.choice(['a', 'b', 'c', 'd'], { size: 2 }); // ['c', 'd']
random.choice(5, { size: 3 }); // [0, 1, 2], drawn from 0 to 4
random.choice(['heads', 'tails'], {
size: 4,
replace: true,
probabilities: [0.8, 0.2],
}); // ['heads', 'tails', 'tails', 'heads']
random.random(); // 0.09697818756103516, uniform on [0, 1)
random.randInt(10); // 7, integer on [0, 10)
random.randInt(5, 10); // 8, integer on [5, 10)
random.randomSample(3); // [0.5125349164009094, 0.30097395181655884, 0.8842552900314331]- a number: seeds an ml-xsadd generator.
- a function returning numbers uniformly distributed on [0, 1).
- nothing: uses
Math.random.
Picks elements from values, an array or a number n (meaning the integers from 0 to n - 1).
| Option | Default | Description |
|---|---|---|
size |
1 |
Number of elements to pick. |
replace |
false |
Put each picked element back in the pool before the next draw. |
probabilities |
uniform | Probability of each element; must have the same length as the values and sum to 1. Needs replace: true. |
random.random(): a number on [0, 1).random.randInt(low, high?): an integer on [low,high), or on [0,low) whenhighis omitted.random.randomSample(size): an array ofsizenumbers on [0, 1).