ActionScript-3 random numbers between max and min

I generate a random number between min and max with this code:

return min + (max - min) * Math.random(); 

And it works. However, random numbers are very small usually between "1 or 3", even if the maximum value is 80.

What is the best way to distribute random numbers over the entire range?

thanks

+7
math random actionscript-3
source share
5 answers

I am very sure that the code you sent is return min + (max - min) * Math.random(); , should return a uniformly distributed random number between min (inclusive) and max (exclusive). There is no reason why it will return between 1 and 3. Have you tried tracking min and max to make sure that they are numbers that you consider them to be?

+7
source share

math.random ()


Math.random () returns a random number between the values โ€‹โ€‹of 0.0 and 1.0 . To create a random integer from 1 to MAX (which I assume U wants), try the following:

 Math.ceil(Math.random()*MAX); 

More on Math.Random ():

Official ActionScript Documentaion

  • To create a random integer between MIN and MAX, try the following:
    MIN + Math.round (Math.random () * (MAX-MIN));

  • To create a random decimal (floating point) between MIN and MAX, try the following:
    MIN + Math.random () * (MAX-MIN));

+2
source share

Try the following:

 package util { public class RandomNumberHelper { public static function randomIntRange(start:Number, end:Number):int { return int(randomNumberRange(start, end)); } public static function randomNumberRange(start:Number, end:Number):Number { end++; return Math.floor(start + (Math.random() * (end - start))); } } } 

...

 protected function testRandomIntsInRange(start:int, end:int):void { var randomIntsAssigned:Object = {}; var randomInt:int = 0; for (var i:int = 0; i < 10000; i++) { randomInt = RandomNumberHelper.randomIntRange(start, end); if (!randomIntsAssigned.hasOwnProperty(randomInt)) randomIntsAssigned[randomInt] = 0; randomIntsAssigned[randomInt]++; } trace(randomIntsAssigned); } 

I get pretty even distributions between 0 and 9 at least.

+1
source share
 number = (400 - (Math.floor(Math.random()*110))); 400 = max 110 = min 
0
source share

try it.

 function randomRange(minNum:Number, maxNum:Number):Number { return (Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum); } 
0
source share

All Articles