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?
I looked through the Rhino source code to find out which pseudo-random function they use. Apparently they fall back to the
Math.randomfunction defined in the Java standard library.The documentation for
Math.randomsays:So I checked the documentation for
java.util.Randomand 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
setSeedmethod says:The actual method used to generate the random number is
nextDouble:The implementation of the
nextDoublefunction is as follows:Clearly it depends on the
nextfunction:The implementation of the
nextfunction 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.