开发者

Random number Absolute 1 or -1

开发者 https://www.devze.com 2023-02-21 04:06 出处:网络
The qu开发者_StackOverflowestion is simple. I need one line command like, Math.round((-Math.random() * 2))

The qu开发者_StackOverflowestion is simple. I need one line command like,

Math.round((-Math.random() * 2))

,which in output just shows 1 and -1. I try to figure it out but it seems not an easy task! I can use IF command like,

demo = (Math.random()>.5)?(1):(-1);

but I need something faster, like a math formula.


If you want a faster way you can do it as this:

var n:Number=(int(Math.random()>=0.5)<<1)-1.0

How it works : Math.random()>=0.5 will return true or false

int(true) = 1
int(false) = 0

<<1 will multiply the value by 2 so you have an int which is 2 or 0

now substract 1.0 and you have a number that is 1.0 or -1.0

Here some live test with their speed: http://wonderfl.net/c/xdqv


I can't imagine anything faster than this:

var n:int = ((Math.random()*4)&2)-1;

No conditionals, no compares, no functions other than random() :-)

And here is another one just to make you think about how it works:

var n:int = (((Math.random()*0xFFFFFFFF) & 0x80000000)>>30) | 1;


Math.round(Math.random())*2-1;

But to be honest it's slower than the conditional method.

var referenceTime:int = getTimer();
var randomInt:int;
for (var i:int=0; i < 1000000; i++)
{
    randomInt = (Math.random()>.5)?1:-1;
}

trace(getTimer()-referenceTime);  //122ms
referenceTime = getTimer();

for (i=0; i < 1000000; i++)
{
    randomInt = Math.round(Math.random())*2-1;
}

trace(getTimer()-referenceTime);   //238ms


Your second line (the ternary operator) is the fastest way to do this. If you're calling this a lot, then you can cache the Math.random() function like:

private var m_ran:Function = Math.random;

Or for the absolute quickest access, you can pregenerate an array of 100 (or 1000, whatever) results, then traverse the list whenever you need it. Something like:

private var m_nums:Vector.<int> = null;
private var m_total:int         = 100;
private var m_curr:int          = 0;

private function _init():void
{
    this.m_nums         = new Vector.<int>( this.m_total, true );
    var ran:Function    = Math.random;
    for( var i:int = 0; i < total; i++ )
        this.m_nums[i] = ( ran() > 0.5 ) ? 1 : -1;
}

public function getRandom():int
{
    this.m_curr++;
    if( this.m_curr >= this.m_total )
        this.m_curr = 0;
    return this.m_nums[this.m_curr];
}


Math.round(Math.random())*(maxValue-minValue+1))+minValue;  

According to jonsca could be a problem to set -1 as integer...


var n:int = int(Math.random()*2) - 1 | 1;
0

精彩评论

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