Okay, so I'm doing some research on how random numbers are generated with the Math.random method. So far I learned that it starts with a "random" seed, and that seed is plugged into some complex equation to create a random number. If the seed is always the same, will the outcome always be the same?
I heard that the seeds for Math.random are generated through the current time, is that correct? They must use the current time all the way down to the mili-seconds or something, because if you didn't you would get the same outcome.
What exactly is the seed? Is it the time such as "10:45" or the time AND date such as "10:45 11/8/12" or some combination?
How can I find the seed, so I can predict the output?
I want to be able to plug this:
alert(Math.floor((Math.random()*10)+1));
into my url bar, and be able to predict the result. Is that possible?
it's likely that there's more to the seed than the millisecond count, because you can call Math.random() many times in the same millisecond and it will return a different value each time.
My output:
If I were implementing it I might make the initial seed based on a millisecond count, and then add 1 each time it's called, so that you wouldn't get the same seed value twice.
Here's a 100% accurate way of predicting the output from
Math.random()
:Now
Math.random()
will always return.5
.The seed is a numeric value, so my guess is that it would be what you get if you call
Date.now()
(ornew Date().getTime()
for older browsers).However, I'm not sure when that seed is taken, or if the seed is isolated to the current page or common to the entire browser process. Predicting random numbers is supposed to be very hard or impossible, that's the whole point of them being random.
No, you cannot predict the seed, but you can preemtively generate enough numbers in order to accurately brute force a match.
Anyhow, start of by reading the wiki page on RNG's - http://en.wikipedia.org/wiki/Random_number_generation, the look at the practical implementations of PRNG's.
I looked through the Rhino source code to find out which pseudo-random function they use. Apparently they fall back to the
Math.random
function defined in the Java standard library.The documentation for
Math.random
says:So I checked the documentation for
java.util.Random
and found this (for the default constructor):So now we know for sure that the seed is the current time in milliseconds. Also, the documentation for the second constructor says:
The documentation for the
setSeed
method says:The actual method used to generate the random number is
nextDouble
:The implementation of the
nextDouble
function is as follows:Clearly it depends on the
next
function:The implementation of the
next
function is as follows:That's the pseudo-random function you are looking for. As it's said in the documentation:
Note however that this is only the random number generator used by Rhino. Other implementations like Spidermonkey and V8 may have their own pseudo-random number generators.