How does this random number generator work?

0

While browsing in through some examples, I ran into this code:

Math.random = function (x) {
  return function () {
    x ^= x << 13;
    x ^= x >>> 17;
    x ^= x << 5;
    return 1 - (x >>> 0) / 0xFFFFFFFF;
  };
}(1);

I don't understand why are these operators used here, why the numbers 13, 17 and 5 are used, and hote does it work.

What I am able to understand is:

  • Since the x parameter is closure to inner returned function, the value 1 passed to it is the seed value.
  • (x >>> 0) / 0xFFFFFFFF is a random decimal decmal in 0 (probably exclusive) and 1 (probably inclusive). So we 1 - the value.

The output of first few runs:

0.9999370498116913

0.9842525718231342

0.3835958974397732

0.928381365008741

0.44151164182496994

javascript
random
bit-manipulation
asked on Stack Overflow Dec 30, 2019 by PranshuKhandal • edited Dec 30, 2019 by PranshuKhandal

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0