A collection of random number generators.
npm install @n7e/rngA collection of random number generators.
For further insights, read on.
- Installation
- Random Number Generator
- Linear Congruential Generator
To install this library use your favorite package manager. No additional
steps are required to start using the library.
``shell`
npm install @n7e/rng
*This library is implemented in TypeScript but can be used with JavaScript
without any additional steps.*
This library provides an interface that all random number generators implement.
This allows the selection of a specific algorithm to be deferred or changed at a
later time without changing the code using the random number generator.
Here is a short example of using a random number generator:
`typescript
import type { RandomNumberGenerator } from "@n7e/rng";
function someFunction(generator: RandomNumberGenerator): number {
const max = 5;
const min = -5;
const clampedRandomNumber = Math.floor(generator.next() * (max - min) + min);
// ...
}
`
You can easily supply any appropriate random number generator you wish when
calling the function:
`typescript
import { LinearCongruentialGenerator } from "@n7e/rng";
someFunction(new LinearCongruentialGenerator());
`
A linear congruential generator
generates numbers using a discontinuous piecewise linear equation. The
constructor provides sensible default values for the equation, so using it is as
easy as:
`typescript
import { LinearCongruentialGenerator } from "@n7e/rng";
const randomNumberGenerator = new LinearCongruentialGenerator();
console.log(randomNumberGenerator.next());
`
You can supply custom values for the equation like so:
`typescript
const randomNumberGenerator = new LinearCongruentialGenerator(
0, // Initial seed, default: Date.now(),
9, // Modulus used in recurrence relation equation, default: 2 ** 31 (used by glibc).
2, // Multiplier used in recurrence relation equation, default: 1103515245 (used by glibc).
0 // Increment used in recurrence relation equation, default: 12345 (used by glibc).
);
console.log(randomNumberGenerator.next());
``