Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Math.random() work in javascript?

I recently figured out how to get a random number via google, and it got me thinking how does Math.random() work. So here I am I can not figure out how they did Math.random() unless they used a time like thing does anyone know how JavaScript's Math.random() works or an equivalent?

like image 537
user2925490 Avatar asked Nov 20 '13 23:11

user2925490


People also ask

How random is JS Math random?

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 generate a number?

[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.

What does Math random () 0.5 do?

random() - 0.5) , returns with equal probability that the first number is greater than the second, or vice versa, which makes the shuffle work much better.

What does Math random () * 100 do?

random returns with 100 will result in a max value of 99.999.... and when cast to an int turns to 99. Since the randomly generated number is supposed to include 100 you'll have to multiply with 101. Multiplying with 100 will result in a max int value of 99.


1 Answers

Math.random() returns a Number value with a 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.

Here's V8's implementation:

uint32_t V8::Random() {      // Random number generator using George Marsaglia's MWC algorithm.     static uint32_t hi = 0;     static uint32_t lo = 0;      // Initialize seed using the system random(). If one of the seeds     // should ever become zero again, or if random() returns zero, we     // avoid getting stuck with zero bits in hi or lo by reinitializing     // them on demand.     if (hi == 0) hi = random();     if (lo == 0) lo = random();      // Mix the bits.     hi = 36969 * (hi & 0xFFFF) + (hi >> 16);     lo = 18273 * (lo & 0xFFFF) + (lo >> 16);     return (hi << 16) + (lo & 0xFFFF); } 

Source: http://dl.packetstormsecurity.net/papers/general/Google_Chrome_3.0_Beta_Math.random_vulnerability.pdf

Here are a couple of related threads on StackOverflow:

  • Why is Google Chrome's Math.random number generator not *that* random?
  • How random is JavaScript's Math.random?
like image 77
Nick Avatar answered Oct 04 '22 04:10

Nick