Languages
[Edit]
EN

JavaScript - custom random numbers generator (Xorshift algorithm implementation)

9 points
Created by:
Blessing-D
604

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
}

 

See also

  1. JavaScript - custom random numbers generator (LCG algorithm implementation / Linear Congruential Generator)

References

  1. https://en.wikipedia.org/wiki/Xorshift

Alternative titles

  1. JavaScript - own random numbers generator (Xorshift 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