Scott Ruttencutter - What The Flash?

Digital Complement to the Moleskine
  • rss
  • Home
  • About

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.

Categories
Flash
Comments rss
Comments rss
Trackback
Trackback

« Using fl.* library within Flex Builder 3 for Mac Using Flash Components in Flex Builder »

2 responses

@Scott-- This is perfect. Had a project I was having

shawn

@Scott– This is perfect. Had a project I was having this exact problem with thanks for the help!

I assumed Math.Round would solve the problem of not reaching

Kayomarz

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.

Leave a comment

You can use these tags : <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Categories

  • Amazing Work
  • Cliché
  • Flash
  • PHP
  • Uncategorized

Links

  • IQ Foundry
  • IQ Games
  • Sticker Foundry
  • Time IQ

Meta

  • Log in
  • Entries RSS
  • Comments RSS
rss Comments rss valid xhtml 1.1 powered by Wordpress get firefox