• About
  • iOS Links

Scott Ruttencutter – Madison, WI iPhone Developer and Creative Technologist



Monthly Archives: December 2009

True Random Integers in Flash AS3

Posted on December 30, 2009 by Scott Ruttencutter

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.

Posted in Flash | 9 Comments |

Pages

  • About
  • iOS Links

Categories

  • Amazing Work
  • Cliché
  • Cocos2D
  • Flash
  • iDevBlogADay
  • iOS
  • PHP
  • Uncategorized

Meta

  • Log in
  • Entries RSS
  • Comments RSS
  • WordPress.org

Pages

  • About
  • iOS Links

Archives

  • October 2013
  • August 2013
  • December 2011
  • October 2011
  • September 2011
  • May 2011
  • October 2010
  • May 2010
  • March 2010
  • December 2009
  • May 2009
  • January 2009
  • December 2008
  • August 2008
  • June 2008
  • May 2008
  • April 2008

Categories

  • Amazing Work (1)
  • Cliché (1)
  • Cocos2D (2)
  • Flash (6)
  • iOS (10)
    • iDevBlogADay (6)
  • PHP (2)
  • Uncategorized (4)

WordPress

  • Log in
  • WordPress
CyberChimps

CyberChimps

© Scott Ruttencutter - Madison, WI iPhone Developer and Creative Technologist