Search code examples
javascriptnode.jsrandom

When does Math.random() start repeating?


I have this simple test in nodejs, I left it running overnight and could not get Math.random() to repeat. I realize that sooner or later the values (or even the whole sequence) will repeat, but is there any reasonable expectancy as to when it is going to happen?

let v = {};
for (let i = 0;; i++) {
  let r = Math.random();
  if (r in v) break;
  v[r] = r;
}
console.log(i);

Solution

  • It is browser specific:

    https://www.ecma-international.org/ecma-262/6.0/#sec-math.random

    20.2.2.27 Math.random ( ) Returns a Number value with positive sign, greater than or equal to 0 but less than 1, chosen randomly or pseudo randomly with approximately uniform distribution over that range, using an implementation-dependent algorithm or strategy. This function takes no arguments.

    Each Math.random function created for distinct code Realms must produce a distinct sequence of values from successive calls.

    The requirement here is just pseudo-random with uniform distribution.

    Here's a blog post from V8 (Chrome and NodeJs's Javascript Engine).

    https://v8.dev/blog/math-random

    Where they say they are using xorshift128+, which has a maximal period of 2^128 -1.