Last week I was working on a project that relied on generating random numbers. I went online to research the Math.random() function but could not find a single, definitive site explaining the many variations of the random function. I thought it might be of some value to consolidate the variety of forms I found.
The most basic code generating a random number generates a ‘pseudo-random’ number greater than or equal to 0 and less than 1. Adobe classifies the results as pseudo-random “because the calculation inevitably contains some element of non-randomness”.
var num:Number = Math.random(); // results: 0.6722401881590486 |
A more versatile usage is to multiply the results by a whole number and then use either the round, ceil or floor functions to convert the result to a whole number. In the program below, squares are randomly placed on a stage that measures 550px x 400px.
for ( var i:uint=0; i<60; i++ ) { // draw rectangle var s:Sprite = new Sprite() s.graphics.beginFill( 0xff0000 ); s.graphics.drawRect( 0, 0, 10, 10 ); s.graphics.endFill(); // place randomly on stage s.x = Math.round( Math.random() * 550 ); s.y = Math.round( Math.random() * 400 ); // add to display order addChild( s ); } |
We can also use Math.random() to select a random color.
for ( var i:uint=0; i<60; i++ ) { // draw rectangle var s:Sprite = new Sprite(); // generate random color var fill:uint = Math.random() * 0xffffff; // fill rectangle with randomly generated color s.graphics.beginFill( fill ); s.graphics.drawRect( 0, 0, 10, 10 ); s.graphics.endFill(); // place randomly on stage s.x = Math.round( Math.random() * 550 ); s.y = Math.round( Math.random() * 400 ); // add to display order addChild( s ); } |
A final form of the function defines a range of random numbers.
// var num:uint = Math.round( Math.random() * ( maxValue - minValue )) + minValue; var num:uint = Math.round( Math.random() * ( 3 - 1 )) + 1; trace( num ); // yields random values between 1 and 3 |
Hope this helps…
No Comments so far ↓
There are no comments yet...Kick things off by filling out the form below.