lundi 30 décembre 2019

How does this random number generator work?

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);

But now, I am unable to understand how it works.

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




Aucun commentaire:

Enregistrer un commentaire