Monday 14 July 2008

Javascript Random Numbers

OK then, to generate a random number in javascript you need to use

Math.random()

which produces a number between 0 and 1.

I began by multipling the random number by the maxmium value to give a random number in a range. So for a number between 0 and 4,

Math.round(Math.random()*4)

However this will not give you a true result for 0 or 4, as the rounding for 0 and 4 will have half the possible candidate random numbers.
So another possibility is to use floor instead of round and use the range instead of the max value.

Math.floor(Math.random()*5)

This is floored in principle if the random number returns 1, which is a 1 in a gazillion billion chance. (Haven't actually proved 1 is a possible return value, but assuming it is) So to be clinically correct we can mod the result to always give a value answer.

Math.floor(Math.random()*5)%5

And an example to prove the spread of random numbers:

<html><body>
<script>
var a = new Array(0,0,0,0,0);
for(i=0;i<1000;i++)
{
a[Math.floor(Math.random()*5)%5] += 1;
}
document.write(a+"<br/>");
document.write("Total: "+(a[0]+a[1]+a[2]+a[3]+a[4]));
</script>
</body></html>

Javascript Random Numbers ... Done.

No comments: