True Random Integers in Flash AS3
So many people have this wrong, I have to post something right about this. I’m going to show you the example below and explain to you why it’s WRONG, and the simple change in logic required to make true random number generation happen for you.
THIS IS WRONG
var myRandomNumber:Int = Math.floor(Math.random()*(High-Low))+Low;
For example, if you wanted a number between 2 and 10:
var myRandomNumber:Int = Math.floor(Math.random()*(10-2))+2;
You will never get 10 as an answer.
Here is why:
The Math.random() function in AS3 returns a pseudo-random number, where 0 <= n < 1. This means you will never get 1 as your result of calling Math.random(). Without 1, you will never get any number greater than 10 to round down to 10. Everybody and their mom has the above formula as the 'correct' way to get a ranged integer number out of the Math.random() function. So why not use Math.ceil, or Math.round? Math.ciel will give you the same problem, but at the beginning of your number range. Math.round sounds great, except you'll be left with 50% less chances to receive either your top or bottom number. So what's the solution? Easy. Add 1 inside your Math.floor call before you multiply with your random number. Then everything will have the same odds. THIS IS RIGHT
var myRandomNumber:Int = Math.floor(Math.random()*(1+High-Low))+Low;
Think about it. Use it. And if there is a better way to do this, let me know. If I’m wrong, please tell me. I love to know when I’m wrong.