Languages
[Edit]
EN

JavaScript - custom random numbers generator (SplitMix64 algorithm implementation)

8 points
Created by:
Wesley
531

In this article, we're going to have a look at how to write own implementation of random numbers generator that is based on SplitMix64 algorithm in JavaScript.

Implementation

// ONLINE-RUNNER:browser;

function SplitMix64Randomizer(_seed) {
  	if (_seed == null) {  // null or undefined
        _seed = Date.now();
    }
	let _base = _seed; 
    // Returns unsigned 32-bit integer.
    //
    this.nextInt = () => {
      	_base = (_base + 0x9e3779b9) | 0x00000000;
        let z = _base;
        z ^= z >>> 16;
        z = Math.imul(z, 0x21f0aaad);
        z ^= z >>> 15;
        z = Math.imul(z, 0x735a2d97);
        z ^= z >>> 15;
        return z >>> 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 SplitMix64Randomizer(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 SplitMix64Randomizer();

    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
}

 

Alternative titles

  1. JavaScript - own random numbers generator (SplitMix64 algorithm implementation)
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join