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.

9 Comments on “True Random Integers in Flash AS3

  1. I assumed Math.Round would solve the problem of not reaching the HIGH (if you use Math.floor) or LOW (if you use Math.ceil) values.

    Only until I read your post and saw that it would get the HIGH or LOW values but with 50% less probability.

    Thanks.

  2. Scott, thank you for this helpfull blog. I was wondering if you know how to do the following, I want to create a small application in which the user can set the range of the random numbers by entering numbers in a text field, and than generate a random number between those values.

    I hope you can help!?

    Kind regards,

    Rick

  3. randomNumberText.text = (Math.ceil(Math.random()*(high-low))+low).toString();

    works without the +1 hack, i’m not AS expert, i just have had a little bit of experience using Math.ceil, which rounds up, enabling you to get that max number in the number range…

  4. hi = 2
    lo = 1

    r = (Math.ceil(Math.random()*(2-1))+1)

    or

    r = (Math.ceil(Math.random()*1)+1)

    I think giving you a result between 2 and 2, which doesn’t seem like what you want.

Leave a Reply

Your email address will not be published. Required fields are marked *

*