开发者

increase chances of even number

开发者 https://www.devze.com 2023-03-04 04:12 出处:网络
If I am getting a random 开发者_Python百科number, how do I increase my chances of making that random number to be even. I am not looking to make it even every time. I am just looking to generate a ran

If I am getting a random 开发者_Python百科number, how do I increase my chances of making that random number to be even. I am not looking to make it even every time. I am just looking to generate a random number say... %70 of the time or %90 of the time.

    private function randNum (high, low) {
        return Math.floor(Math.random() * (1+high-low)) + low;
    }

Would I pass in a greater range of numbers to this function? Or would I have to scrap this function altogether?

Thank you


private function randNum (high : Number, low : Number) : int
{
    var even : Boolean = Math.random() < 0.7; //set probability of even number here
    var rand : int = Math.floor(Math.random() * (1+high-low)) + low;
    if (even)
        while (rand % 2 != 0)
            rand = Math.floor(Math.random() * (1+high-low)) + low;
    else
        while (rand % 2 != 1)
            rand = Math.floor(Math.random() * (1+high-low)) + low;
    return rand;
}

Test:

var even : int = 0;
var odd : int = 0;
for (var i : int = 0; i < 100000; i++)
{
    var a : int = randNum(1, 20);
    if (a % 2 == 0)
        even++;
    else
        odd++;
}
trace(even, odd);

Output:

[trace] 69869 30131


A little too late ;) but another one with no loop and using bit masking operation :

ret & -2 will make your number even, then depending on the result of (Math.random() >= evenProbability) you set the lower bit to be 1 to give an odd number

function randomRange(low:int, high:int, evenProbability:Number = 0.5):int{
     var ret:int = int( Math.random() * ( 1 + high - low ) ) + low
     return ( ret & -2 ) | int( Math.random() >= evenProbability )
}

Here a live test with wonderfl : http://wonderfl.net/c/9IHx

0

精彩评论

暂无评论...
验证码 换一张
取 消