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 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
}

 

See also

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

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