Math.random() * Math.random()

Actionscript:
  1. 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:

Actionscript:
  1. [SWF(width=800, height=600)]
  2.  
  3. var r:Number = Math.random() * Math.random() * Math.random();
  4. var inc:int = 0;
  5. var xp:Number = 10;
  6. var yp:Number = 10;
  7. var count:int = 1;
  8.  
  9. var compare:Shape = Shape(addChild(new Shape()));
  10. compare.graphics.lineStyle(0,0x2222FF);
  11.  
  12. graphics.lineStyle(0,0x00000);
  13. scaleX = scaleY = 2;
  14.  
  15. addEventListener(Event.ENTER_FRAME, onLoop);
  16. function onLoop(evt:Event):void {
  17.    
  18.      r =  Math.random() * Math.random() * Math.random();
  19.  
  20.      if (inc == 0){
  21.          graphics.moveTo(xp + inc, yp + 30 - r * 30);
  22.      }else{
  23.          graphics.lineTo(xp + inc, yp + 30 - r * 30);
  24.      }
  25.      
  26.      r = Math.random();
  27.       if (inc == 0){
  28.          compare.graphics.moveTo(xp + inc, yp + 70 - r * 30);
  29.      }else{
  30.          compare.graphics.lineTo(xp + inc, yp + 70 - r * 30);
  31.      }
  32.      inc++;
  33.      if (inc == 50){
  34.          inc = 0;
  35.          xp = 10 + count % 6 * 60;
  36.          yp = 10 + int(count / 6) * 80;
  37.          r = Math.random()*Math.random();
  38.          count++;
  39.      }
  40. }

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

This entry was posted in one-liners, random and tagged , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

2 Comments

  1. Posted July 15, 2009 at 1:44 pm | Permalink

    This kind of multiplication transforms a uniform pseudo-random number generator in a “normal alike” pseudo-random number generator, with mean=0.5. That’s why 0 and 1 are less frecuent than values between them.

  2. Posted July 15, 2009 at 1:51 pm | Permalink

    Thanks for the info Ignacio… I had a feeling there was a name for what I was doing… can you do the same thing without multiplication and conditionals?

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*