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?
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.
[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.
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.
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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With