Back on topic. Got a real doozy for you today. This simple lesson can have some huge impact on the integrity of your Flash or javascript apps. I recently found out that I’ve been using a faulty random number function for ages. Take a look and see how one little function can make a huge difference.
Watch the video
It seems the randomNumber function I have been using to get a random number between a low and high value is very biased AGAINST the numbers at the far ends of the spectrum. Simply put, if I want a random number between 1 and 5 the chance that a 1 or 5 will show up is MUCH LESS than getting a 2,3, or 4.
The Faulty Function (NEVER USE THIS AGAIN)
function randomNumber(min:Number, max:Number):Number {
//bad
return Math.round(Math.random() * (max - min) + min);
}
The Accurate ActionScript 3 Random Number Function
function randomNumber(min:Number, max:Number):Number {
//good
return Math.floor(Math.random() * (1 + max - min) + min);
}
To use this function to generate a value between any where between and including 1 and 5
randomNumber(1,5);
Learn More
To read about the details of the function visit Kirupa: Random Numbers by Scott Ruttencutter
Special thanks to Matthew Lein for making me aware of this issue. Check out Matt’s JavaScript Experiments. He does really cool stuff with js.
Still unclear? scroll up and watch the video again:)
Download my test file used in the video
Thanks for watching. For a fun time, click each one of the pretty buttons below:






