Kevbear
Kevbear

Reputation: 351

Actionscript 3.0 use Math.random()

Actionscript to use Math.random what will this mean Right = 6 + Math.random() * 2;

I know Math.random is between 0-0.99... but will it come out (6 - 7)?

Upvotes: 0

Views: 181

Answers (2)

Craig
Craig

Reputation: 459

I prefer to write a function to set the scale and range for you. Like this:

public static function getRandomNumber(low:Number=0, high:Number=1):Number
{
    return Math.floor(Math.random() * (1+high-low)) + low;
}

Now you can call it:

getRandomNumber(6, 7); //returns 6-7 inclusive

Upvotes: 1

taskinoor
taskinoor

Reputation: 46027

Math.random() returns a number greater or equal to 0 and less than 1.0, i.e.

0 <= Math.random() < 1.0

If we multiply this with b then we get a number greater or equal to 0 and less than b, i.e.

(0 * b) <= (Math.random() * b) < (1.0 * b)

or 0 <= (Math.random() * b) < b

If we add a with this then we get a number greater or equal to a and less than a + b, i.e.

(a + 0) <= (a + Math.random() * b) < (a + b)

or a <= (a + Math.random() * b) < (a + b)

So, 6 + Math.random() * 2 returns a number greater or equal to 6 and less than 8. If you assign this to an integer then it will be either 6 or 7.

Upvotes: 3

Related Questions