5.7. Generating a Random Number

Problem

You want to generate a random number within a certain range.

Solution

Use Math.random( ) as the basis for a custom randRange( ) method.

Discussion

You can use the Math.random( ) method to generate a random floating-point number from 0 to 0.999999999. In most cases, however, programs call for a random integer, not a random floating-point number. Furthermore, you may want a random value within a specific range. If you do want a random floating-point number, you will ordinarily want to specify its precision (the number of decimal places).

Here is the basic process for generating random numbers of this type:

  1. Calculate the range difference and then add 1. For example, if you want to generate random numbers between 4 and 10, the range is 10-4 (which equals 6). To ensure an equal distribution, add 1 to this range.

  2. If you want the random number to include decimal places, multiply the range by the correct multiple of 10 prior to adding 1. For example, to create random numbers with one decimal place, multiply the range by 10. To create random numbers with two decimal places, multiply the range by 100, etc.

  3. Multiply the value from step 2 by the value returned by Math.random( ). This will give you a value between 0 and the value from step 2 (with decimal places).

  4. Use the Math.floor( ) method to get the integer part of the value from step 3.

  5. Divide the result from step 4 by the same multiple of 10 that you used in step 2. For example, if you originally multiplied ...

Get Actionscript Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.