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 CustomRandom(seed) {
if (seed == null) { // null or undefined
seed = Date.now();
} else {
if (seed < 1) {
throw new Error('Seed value must be positive.');
}
}
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 random = new CustomRandom(3819201); // 3819201 is example initial seed
console.log(random.nextInt()); // 1420432560
console.log(random.nextInt()); // 3519015534
console.log(random.nextInt()); // 2998255351
}
// Usage example 2 (values should always be different):
{
const random = new CustomRandom();
console.log(random.nextInt()); // 1961511945
console.log(random.nextInt()); // 2416256316
console.log(random.nextInt()); // 2700432077
console.log(random.nextDouble()); // 0.37185698639877535
console.log(random.nextDouble()); // 0.9140633675069696
console.log(random.nextDouble()); // 0.5699877602909663
}