From: www.itworld.com

Randomness Simplified

by David Wall

July 1, 2002 —

 

The Math.random() method returns a pseudorandom number between 0 and 1.
That, like the office of the American vice president, is pretty close to
being useful, but not quite.

They call it a pseudorandom number because an algorithm generates the
numbers, which means it's predictable. Given the right conditions, you
can get the same sequence of pseudorandom numbers from Math.random(). To
get truly random values, you need a hardware device observing something
well and truly unpredictable, such as static in the radio frequencies.
Most computers don't have such random-number generation devices, so
pseudorandom numbers have to do for us.

Math.random() will, however, generate a pseudorandom number between 0
and 1, which takes us about halfway to a useful number. Here's a
solution that returns a random number between any upper and lower limits
you care to send to it:

function returnRandom(lower, upper) {
var range = upper-lower+1;
var l = ("" + range).length;
var randomNumber = (Math.floor(Math.random() * Math.pow(10,l)) %
range) + parseInt(lower);
return randomNumber;
}

Remember that Math.pow() returns the value of its first parameter raised
to the power of its second parameter. Math.pow(3,2) would indicate three
squared, or nine.

So, we're finding in this algorithm the number of "places" in the number
of potential responses we're choosing from. If we need a number between
1 and 100, for example, the number of places is three. We then raise 10
to that power, multiply it by the result of Math.random(), round that
down, and mod it by the difference between the upper and lower values.
Add the lower limit to that, and you have a random number within your
parameters.