• Math.random() * Math.random() in AS3
    var rand:Number = Math.random() * Math.random() * Math.random();

    This is a trick I use when I need more contrast in my random numbers. In this case, the variable rand will get closer to the number 1 significantly less frequently than if you just used Math.random() once.

    To illustrate this I created this snippet:


    [SWF(width=800, height=600)]
    var r:Number = Math.random() * Math.random() * Math.random();
    var inc:int = 0;
    var xp:Number = 10;
    var yp:Number = 10;
    var count:int = 1;
    var compare:Shape = Shape(addChild(new Shape()));
    compare.graphics.lineStyle(0,0x2222FF);
    graphics.lineStyle(0,0×00000);
    scaleX = scaleY = 2;
    addEventListener(Event.ENTER_FRAME, onLoop);
    function onLoop(evt:Event):void {
    r =  Math.random() * Math.random() * Math.random();
    if (inc == 0){
    graphics.moveTo(xp + inc, yp + 30 – r * 30);
    }else{
    graphics.lineTo(xp + inc, yp + 30 – r * 30);
    }
    r = Math.random();
    if (inc == 0){
    compare.graphics.moveTo(xp + inc, yp + 70 – r * 30);
    }else{
    compare.graphics.lineTo(xp + inc, yp + 70 – r * 30);
    }
    inc++;
    if (inc == 50){
    inc = 0;
    xp = 10 + count % 6 * 60;
    yp = 10 + int(count / 6) * 80;
    r = Math.random()*Math.random();
    count++;
    }

    }

    The blue lines plots normal Math.random() and the black lines plots Math.random()*Math.random()*Math.random()

    This entry was posted on Tuesday, October 27th, 2009 at 7:17 am and is filed under ActionScript, Flash, Tutorials. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

    You might also like

    Tricks and Experiments , AS3 Tips As you read each of the following descriptions, consider opening Flash, pasting the code into timeline script and...
    Using other types within ActionScript packages I was doing something, I forget what it was now, but it got me curious about functions defined in some of the...
    Compass Effect in AS3 We show how to create a draggable compass in AS3. We use tweening as our primary tool. There is a number of trigonometric...
    printf function for ActionScript3 Function for doing string variable substitutions in AS3. Inspired by python's print and strtime. This is...
  • 0 Comments

    Take a look at some of the responses we've had to this article.

  • Post a Comment

    Let us know what you thought.

  • Name:

    Email (required):

    Website:

    Message: