Seeded Random Number Generator

3.0.5 · maintenance · verified Sun Apr 19

Seedrandom is a JavaScript library that provides seeded pseudorandom number generators (PRNGs). It allows developers to create reproducible sequences of 'random' numbers, which is crucial for deterministic simulations, testing, and specific cryptographic applications (though caution is advised for security-sensitive contexts due to common misuse patterns). The current stable version is 3.0.5, released in late 2019, suggesting a mature but slow-moving maintenance cadence. Key differentiators include its ability to replace the global `Math.random` for debugging or testing purposes, and its inclusion of various PRNG algorithms (such as ARC4, Alea, xor128, Tyche-i) offering different performance characteristics and period lengths. It supports use in web browsers via script tags, as a Node.js module, and as an AMD module. Developers can instantiate independent PRNGs or opt to globally override `Math.random` with a seeded sequence.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates creating independent seeded PRNG instances using the default ARC4 algorithm and the Alea algorithm. Also illustrates the critical warning regarding globally overriding `Math.random`.

import seedrandom from 'seedrandom';

// Create an independent, seeded PRNG instance
const myrng = new seedrandom('my-secret-seed');
console.log('Seeded PRNG instance results (ARC4):');
console.log(myrng()); // Always the same for this seed
console.log(myrng()); // Always the same subsequent value

// Demonstrating other PRNGs (Alea algorithm)
import Alea from 'seedrandom/lib/alea';
const aleaRng = new Alea('another-seed'); // Alea requires an explicit seed
console.log('\nSeeded PRNG instance results (Alea):');
console.log(aleaRng());
console.log(aleaRng.double()); // Alea can provide 56 bits of randomness

// --- WARNING: Global Math.random override example ---
// This directly modifies the global Math.random, making it predictable.
// This should only be used for controlled testing and must be restored.
console.log('\nGlobal Math.random override (WARNING!):');
const originalMathRandom = Math.random; // Save original Math.random
seedrandom('global-override-seed'); // Calling without 'new' or assignment overrides Math.random
console.log(Math.random());
console.log(Math.random());

// Restore original Math.random after demonstration to prevent side effects
Math.random = originalMathRandom;
console.log('\nMath.random restored to original behavior.');

view raw JSON →