Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is randomness achieved with Math.random in javascript?

How is randomness achieved with Math.random in javascript? I've made something that picks between around 50 different options randomly. I'm wondering how comfortable I should be with using Math.random to get my randomness.

like image 776
David Avatar asked Feb 26 '10 19:02

David


People also ask

How random is Math random in JavaScript?

How random is Math. random()? It may be pointed out that the number returned by Math. random() is a pseudo-random number as no computer can generate a truly random number, that exhibits randomness over all scales and over all sizes of data sets.

How does Math random work internally?

random() 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.

Is JavaScript random actually random?

In JavaScript, random() is a built-in method that is used to return a random number in the range 0 to 1 (with 0 being inclusive and 1 exclusive). The distribution of the generated random numbers is approximately uniform. It does not actually return a whole number. Instead, it returns a floating point (decimal) value.


2 Answers

From the specifications:

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.

So the answer is that it depends on what JavaScript engine you're using.

I'm not sure if all browsers use the same strategy or what that strategy is unfortunately

It should be fine for your purposes. Only if you're doing a large amount of numbers would you begin to see a pattern

like image 99
Bob Avatar answered Oct 20 '22 14:10

Bob


Using Math.random() is fine if you're not centrally pooling & using the results, i.e. for OAuth.

For example, our site used Math.random() to generate random "nonce" strings for use with OAuth. The original JavaScript library did this by choosing a character from a predetermined list using Math.random(): i.e.

for (var i = 0; i < length; ++i) {
    var rnum = Math.floor(Math.random() * chars.length);
    result += chars.substring(rnum, rnum+1);
}

The problem is, users were getting duplicate nonce strings (even using a 10 character length - theoretically ~10^18 combinations), usually within a few seconds of each other. My guess this is due to Math.random() seeding from the timestamp, as one of the other posters mentioned.

like image 37
Nick Baicoianu Avatar answered Oct 20 '22 15:10

Nick Baicoianu