Actionscript-3 random numbers between max and min

2019-04-26 19:13发布

I'm generating a random number between min and max with this code:

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

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

How can I better distribute the random numbers over all range ?

thanks

5条回答
爷、活的狠高调
2楼-- · 2019-04-26 19:39

I am very sure that the code you posted, return min + (max - min) * Math.random(); , should return an evenly distributed random number between min (inclusive) and max (exclusive). There is no reason why it would return between 1 and 3.. Did you try tracing min and max to make sure that they are the numbers you think they are?

查看更多
趁早两清
3楼-- · 2019-04-26 19:40

Math.Random()


Math.random() returns a random number between the values of 0.0 and 1.0. To generate a random integer between 1 and MAX (which i assume U want), Try this:

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

For More on Math.Random() refer:

Official Actionscript Documentaion

  • To generate a random integer between MIN and MAX, Try this:
    MIN + Math.round(Math.random()*(MAX-MIN));

  • To generate a random decimal (floating-pt number) between MIN and MAX, Try this:
    MIN + Math.random()*(MAX-MIN));

查看更多
在下西门庆
4楼-- · 2019-04-26 19:44

Try this:

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 am getting fairly even distributions between 0 and 9 at least.

查看更多
Deceive 欺骗
5楼-- · 2019-04-26 19:45
number = (400 - (Math.floor(Math.random()*110)));

400 = max
110 = min
查看更多
Deceive 欺骗
6楼-- · 2019-04-26 19:49

try this.

function randomRange(minNum:Number, maxNum:Number):Number 
{
    return (Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum);
}
查看更多
登录 后发表回答