Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the chances that JavaScript Math.Random() will create the same number twice in a row?

Is this correct? using - http://en.wikipedia.org/wiki/Binomial_probability

Looks like values are from .0000000000000000 to .9999999999999999

Probability of happening twice = p^2 = (1/9999999999999999)^2 = 1.0 e-32

I think I am missing something here?

Also, how does being a pseudo random number generator change this calculation?

Thank You.

like image 200
T.T.T. Avatar asked Dec 16 '10 01:12

T.T.T.


People also ask

Can Math random returns same number?

random() returns same sequence of numbers [SOLVED] While messing around with Math. random() in the lesson, on the scratch pad, and in the Codecademy Labs, I found that it generates the exact same sequence of numbers.

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.

Is Math random () biased?

The problem with this approach is that it's biased. There are numbers returned that are more likely to occur than others. To understand this, you need to understand that Math. random() is a 32-bit RNG in Chrome and Safari, and a 53-bit RNG in Edge and Firefox.

What is the use of Math random () in JavaScript?

The Math. random() function returns a floating-point, pseudo-random number in the range 0 to less than 1 (inclusive of 0, but not 1) with approximately uniform distribution over that range — which you can then scale to your desired range.


1 Answers

In an ideal world Math.random() would be absolutely random, with one output being completely independent from another, which (assuming p=the probability of any given number being produced) results in a probably of p^2 for any value being repeated immediately after another (as others have already said).

In practice people want Math.random to be fast which means pseudo-random number generators are used by the engines. There are many different kinds of PRNG but the most basic is a linear congruential generator, which is basically a function along the lines of:

s(n + 1) = some_prime * s(n) + some_value mod some_other_prime

If such a generator is used then you won't see a value repeated until you've called random() some_other_prime times. You're guaranteed of that.

Relatively recently however it's become apparent that this kind of behaviour (coupled with seeding the PRNGs with the current time) could be used for some forms tracking have led to browsers doing a number of things that mean you can't assume anything about subsequent random() calls.

like image 177
olliej Avatar answered Oct 21 '22 11:10

olliej