Skip to content
mljsPublic

About

Randomness utilities

Resources

Stars

2 stars

Watchers

7 watching

Forks

Repository files navigation

ml-random

NPM version build status Test coverage npm download

Randomness utilities from a selection of elements.

Installation

$ 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.

Usage

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]

new Random(seedOrRandom?)

  • a number: seeds an ml-xsadd generator.
  • a function returning numbers uniformly distributed on [0, 1).
  • nothing: uses Math.random.

random.choice(values, options?)

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.

Other methods

  • random.random(): a number on [0, 1).
  • random.randInt(low, high?): an integer on [low, high), or on [0, low) when high is omitted.
  • random.randomSample(size): an array of size numbers on [0, 1).

License

MIT

About

Randomness utilities

Resources

Stars

2 stars

Watchers

7 watching

Forks

Releases

Packages

Used by

Contributors

Languages