EN
JavaScript - custom random numbers generator (Xorshift algorithm implementation)
9
points
In this article, we're going to have a look at how to write own implementation of random numbers generator that is based on Xorshift algorithm in JavaScript.
Implementation
// ONLINE-RUNNER:browser;
function XorshiftRandomizer(seed) {
if (seed == null) { // null or undefined
seed = Date.now();
} else {
if (seed < 1 || seed > 4294967295) { // 0xffffffff (hex) === 4294967295 (dec)
throw new Error('Seed value must be from 1 to 4294967295.');
}
}
let x = seed >>> 0;
// Returns unsigned 32-bit integer.
//
this.nextInt = () => {
x ^= x << 13;
x ^= x >>> 17;
x ^= x << 5;
return x >>> 0;
};
// Returns floating-point number from 0.0 (inclusive) to 1.0 (exclusive).
//
this.nextDouble = () => {
const value = this.nextInt();
return value / 0x100000000;
};
}
// Usage example 1:
{
const randomizer = new XorshiftRandomizer(3819201); // 3819201 is example initial seed
console.log(randomizer.nextInt()); // 1420432560
console.log(randomizer.nextInt()); // 3519015534
console.log(randomizer.nextInt()); // 2998255351
}
// Usage example 2 (values should always be different):
{
const randomizer = new XorshiftRandomizer();
console.log(randomizer.nextInt()); // 1961511945
console.log(randomizer.nextInt()); // 2416256316
console.log(randomizer.nextInt()); // 2700432077
console.log(randomizer.nextDouble()); // 0.37185698639877535
console.log(randomizer.nextDouble()); // 0.9140633675069696
console.log(randomizer.nextDouble()); // 0.5699877602909663
}