
Math.round() Method
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
612
|
ActionScript Language Reference
// Note that to simulate two dice, you can use this:
twoDice = myRandom(2, 12); // The minimum value is 2, not 1
// To return the die values separately, use an array
function rollTwoDice () {
return [myRandom(1, 6), myRandom(1, 6)];
}
Due to a bug in Flash Player 5.0.30.0, this approach is prone to an extremely rare, but
potentially important inaccuracy. In Flash Player 5.0.30.0, random( ) generates values in the
range of 0.0 to 1.0, inclusive. When we multiply the return of random( ) by an integer, n,
we produce values in the range of 0.0 to n. In our example, we multiplied Math.random( )
by 6, so that the returned value ranges from 0.0 to 6.0. By invoking floor( ) on the adjusted
value, we produce integers in the range of 0 to n (0 to 6 in our example). The scaling and
rounding leads to an inaccurate distribution of random numbers—the chance of producing
n is much smaller than the chance of producing any other number in the series.
The Math.random( ) was fixed in Flash Player 5.0.41.0. If supporting older versions of the
Player, the following version of the myRandom( ) function avoids the problem by simply
discarding the value 1.0 if it happens to be chosen by Math.random( ):
// Returns an integer in the range of minVal to maxVal ...