Monday, 14 July 2008

Javascript Random Numbers

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


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,


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.


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.


And an example to prove the spread of random numbers:

var a = new Array(0,0,0,0,0);
a[Math.floor(Math.random()*5)%5] += 1;
document.write("Total: "+(a[0]+a[1]+a[2]+a[3]+a[4]));

Javascript Random Numbers ... Done.

No comments: