Mathematically Correct Random Number Generation

2.1.0 · active · verified Tue Apr 21

Random.js is a JavaScript library designed to provide mathematically correct and consistent random number generation, addressing the shortcomings of `Math.random()` and common biased implementations. It offers various 'engines' like `nativeMath` (using `Math.random`), `browserCrypto` (using `crypto.getRandomValues`), `nodeCrypto` (using `crypto.randomBytes`), and `MersenneTwister19937` for deterministic, repeatable sequences. The library focuses on providing 32 bits of randomness consistently and includes distributions to prevent common biases in integer generation. The current stable version is 2.1.0, and while a specific release cadence isn't stated, it generally follows semver for major breaking changes. Its key differentiators include platform-specific cryptographic engines and a robust, bias-free API for various distributions, making it suitable for simulations, games, and other applications where high-quality randomness is crucial.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates importing and initializing a `Random` instance with a `MersenneTwister19937` engine, seeding it for deterministic results, and generating a uniform random integer using the `integer` distribution. It also briefly mentions other engine options.

import { Random, MersenneTwister19937, integer } from 'random-js';

// Initialize a deterministic engine with a seed
const engine = MersenneTwister19937.seed(123);

// Create a Random instance with the engine
const random = new Random(engine);

// Generate a random integer between 1 and 100 (inclusive)
const randomNumber = random.integer(1, 100);
console.log(`Deterministic random number: ${randomNumber}`);

// Demonstrate using a non-deterministic engine (e.g., nodeCrypto in Node.js)
// In a browser, you might use browserCrypto; nativeMath is also an option.
// Note: nodeCrypto and browserCrypto are only available in their respective environments.
// For cross-platform or tests, MersenneTwister19937 is often preferred.

// Example with nodeCrypto (only works in Node.js environment)
// import { nodeCrypto } from 'random-js';
// const cryptoEngine = nodeCrypto;
// const randomCrypto = new Random(cryptoEngine);
// const cryptoNumber = randomCrypto.integer(1, 100);
// console.log(`Cryptographically random number: ${cryptoNumber}`);

// Generate 5 more deterministic numbers
for (let i = 0; i < 5; i++) {
  console.log(`Next deterministic number: ${random.integer(1, 100)}`);
}

view raw JSON →