Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 740
avo Avatar asked Oct 26 '18 05:10

avo


People also ask

Can Math random repeat?

No, while nothing in computing is truly random, the algorithms that are used to create these "random" numbers are make it seem random so you will never get a repeating pattern.

Can Math random generate same number?

The "random" numbers generated by the mathematical algorithm are given a starting number (called the "seed") and always generates the same sequence of numbers. Since the same sequence is generated each time the seed remains the same, the sequence of random numbers is referred to as being a pseudo-random sequence.

Is Math random predictable?

Math. random is actually very predictable, once you know the seed and the iteration (how many numbers were generated since the seed was set).

What does Math random () do?

Math.random() The Math.random() function returns a floating-point, pseudo-random number that's greater than or equal to 0 and less than 1, with approximately uniform distribution over that range — which you can then scale to your desired range.


1 Answers

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.

like image 170
dwjohnston Avatar answered Sep 28 '22 02:09

dwjohnston