Subscribe to Tutorial Feed

Flash and PHP Bible

The Flash and PHP Bible has been released! The book can be found on Amazon or wherever fine books are sold in your area.

The Flash and PHP Bible has a forum for quick support.

Scriptplayground » tutorials » as » Generate random number in ActionScript 3

Generate random number in ActionScript 3

Custom function to generate a random number, using a low to high sampling.

This code snippet focuses on the topic of random numbers. Below is the original (3 years old) method and a new method added just now.

New "updated" Method (2010)

/** 
* Generates a truly "random" number
* @return Random Number
*/ 
function randomNumber(low:Number=0, high:Number=1):Number
{
  return Math.floor(Math.random() * (1+high-low)) + low;
}

Original Method (2007)

/** 
* Generate a random number
* @return Random Number
* @error throws Error if low or high is not provided
*/  
function randomNumber(low:Number=NaN, high:Number=NaN):Number
{
  var low:Number = low;
  var high:Number = high;

  if(isNaN(low))
  {
    throw new Error("low must be defined");
  }
  if(isNaN(high))
  {
    throw new Error("high must be defined");
  }

  return Math.round(Math.random() * (high - low)) + low;
}

Here is how to call the function, just a simple usage.. this can be used for any number of things. Pass in an array length, age range or coordinates.. its up to you

trace("Random Number : " +randomNumber(3, 10));

Follow Scriptplayground on Twitter (@scriptplay)

Comments: Generate random number in ActionScript 3

 jacob  Sat Dec 1, 2007 3:34 am  
why do you set the default values to NaN and throw runtime errors? Doesn't it make more sense to not set default values or make the default between 0 and 100?
 mkeefe  Sun Dec 2, 2007 6:20 pm  
I would have done that except its intended use was random key in an array. However, I do see your point and will make the necessary revision showing both options.
 SimonClark  Mon Mar 3, 2008 7:01 am  
Beware!!!!

This will not produce a truly random spread of numbers. The highest number and the lowest number will get picked 1/2 as frequently as any other number. Use:

Math.floor(Math.random() * (1+high-low)) + low;
 Dick  Sat Oct 11, 2008 3:35 pm  
"Beware!!!!

This will not produce a truly random spread of numbers. The highest number and the lowest number will get picked 1/2 as frequently as any other number. Use:

Math.floor(Math.random() * (1+high-low)) + low; "


is this true? I really don't see how that is true, but i'm just a beginner with as3. can anybody clarify this?
 Dick  Sat Oct 11, 2008 4:48 pm  
Ahh... I must be blind. I see now what you're saying.. thanks for the tip Simon.
 vamapaull  Tue Nov 4, 2008 5:38 am  
great code
very useful
 vamapaull  Tue Nov 4, 2008 5:39 am  
Thank you!
 Nicholas Polet  Mon Dec 29, 2008 2:32 am  
Nice function here, I wrote a similar one in as2 but havent had a chance to convert it to as3, now I dont need to, plus yours is much better.

Thanks for this one
 mkeefe  Sat Jan 10, 2009 6:57 am  
@Nicholas - No problem, glad it worked for you.
 carl  Wed Aug 26, 2009 7:48 pm  
Thanks for sharing this! It sure did save me a lot of time.
 carl  Wed Aug 26, 2009 7:48 pm  
Thanks for sharing this! It sure did save me a lot of time.
 Waqas  Sun Nov 8, 2009 10:14 pm  
Thankyou man ... That was a nice script
 PHANTOMAXWEL  Fri Dec 11, 2009 9:31 am  
This is wrong!
for example if:
low=2
hight=53

Math.round(Math.random() * (high - low)) + low;
will return 54!!!!!!!!!!!!!

You must use:
Math.floor(Math.random() * (high - low)) + low;
 Mendim  Sun Dec 27, 2009 5:56 pm  
@PHANTOMAXWEL

No, you are wrong. It works perfectly. I tested it:

for (var i:uint = 0; i < 1000; i++) {
trace(Custom.rand(45,58));
}

I Ctrl + F'd for any 44's or 59's. I found none.
 Mike  Tue Jan 12, 2010 12:45 pm  
Is there any way to avoid repetition?
 M. P. Junior  Tue Feb 16, 2010 10:01 am  
Hi, i have a solution for random number avoiding repetition.

var ArrayCriaBolas:Array = new Array();
for(var u:uint = 1; u <= 99; u++){
ArrayCriaBolas.push(u);
}
// o Trace abaixo imprime a verificação se o aray esta puxando os numeros certos
//trace("A C B = " + ArrayCriaBolas);

// o While abaixo embaralha os números dentro de novo Array
var ArraySorteiaBolas:Array = new Array(); /* ESSE SERIA O ARRAY DAS BOLAS SORTEADAS */
while (ArrayCriaBolas.length >0) {
var w:int = Math.floor(Math.random()*ArrayCriaBolas.length);
ArraySorteiaBolas.push(ArrayCriaBolas[w]);
ArrayCriaBolas.splice(w,1);
}
 M. P. Junior  Tue Feb 16, 2010 10:03 am  
//verificação do array total
//trace("A S B = " + ArraySorteiaBolas);
 renu  Wed Mar 24, 2010 10:32 pm  
can I generate non repeating random numbers between 1 to 500 in flash cs3.
 Mike  Thu Apr 8, 2010 6:31 am  
If they are non-repeating, doesn't that by definition mean that they're NOT random?

Generating truly random numbers is different than pulling items from an array by randomly selecting their indexes without repetition.
 david  Fri Apr 16, 2010 9:57 am  
Mike, the issue is not the definition of "random" (you are right on that), but a random number from a selection that excludes previously used ones...
 Marco  Mon Jul 19, 2010 5:26 pm  
DO NOT USE THIS FORMULA! It will not give you a truly random result. Use this instead:

Math.floor(Math.random()*(1+High-Low))+Low;

It's a shame this is the first result when I search this topic on Google, and it's wrong. How do we get mkeefe to update to the correct formula?
 Treblah  Sun Jul 25, 2010 8:50 am  
If you don't like the results that are produced with this function and you know how to do it better than do it your way don't sit here and rag on mkeefe, this is probably close enough to random for him, I know it worked fine for what I needed to do. Thanks for the post mkeefe.
 mkeefe  Tue Jul 27, 2010 4:55 am  
@Marco - While I appreciate your input, the reason this tutorial is #1 is because others have used/enjoyed it.

As an aside I have updated the tutorial to reflect comments on this site, thanks all.

 Ömür Yanıkoğlu  Wed Sep 15, 2010 1:27 am  
Thank for this post..
 Jeffrey Penner  Fri Oct 22, 2010 8:49 am  
I am using something similar, however I can not call the number to the if else . Howdo I join the two together. I get a number in the output tab so I know something is working. Here is a bit of my code, I tried to call n last and it did not work.

function randRange(min:Number, max:Number):Number {
var randomNum:Number = Math.floor(Math.random() * (max - min + 1)) + min;
return randomNum;
}
for (var i = 0; i < 1; i++) {
var n:Number = randRange(1, 13)
trace(n);
}

if (n == 1) {
gotoAndPlay (50);
} else if (n == 2) {
gotoAndPlay (50);
} else if (n == 3) {
gotoAndPlay (85);
 mkeefe  Fri Oct 29, 2010 6:47 pm  
@Jeffrey Penner - Why is the call to randRange() in a for..loop? That is probably the issue, that loop will only run once.. not sure the purpose of that.
 Nook  Wed Nov 17, 2010 1:43 am  
You should really only keep the new function as the old one aren't accurate. It has been said (first and last value has 50% of hit compared to the others) and what's worse, the high number will never be picked.

Reason is if you put in 0 as low and 9 as high, that's actually 10 values. So therefore you need the (high - low + 1).

Regarding chance.
Math.random produces a number equal or greater than 0 and less than 1 (0 >= n < 1). So if you devide that range in 10 parts you get:
1st: 0 - 0.09999..
2nd: 0.1 - 0.19999..
3rd: 0.2 - 0.29999..
..
10th: 0.9 - 0.99999..

Now multiply by 10. If you now do a round() the first value will only be picked in the range 0 -> 0.49999.., while the second value will be picked in the range 0.5 - 1.49999... Same with last, it will only be picked in the range 9.5 - 9.9999..
Therefore you need the floor().
 voidreamer  Wed Jan 26, 2011 5:35 am  
Thanks a lot man, really useful your last method
 Chris Moeller  Fri Feb 25, 2011 10:21 am  
Thanks for posting this!
It's the first one I find when I need to remember the best way to do random numbers in as3 (so I see this every few weeks or so).

Chris Moeller
 Mike Heavers  Tue Apr 5, 2011 8:36 am  
Sorry - how do you "use" the number that is returned? Like what would be the trace statement for the value returned in the "2010" example?
 mkeefe  Tue Apr 5, 2011 9:40 pm  
@Mike Heavers - Here is a sample:


var rand:int = randomNumber(0, 10);
trace("Random Number: " + rand);


Hope that helps.
Matt
 Mike Heavers  Thu Apr 7, 2011 8:29 am  
Thanks! Nice, easy to remember formula.
Add a comment
The ability to add new comments has been disabled in this archived version.

Loading
Main | Tutorials | Articles