Recipe 5.7 Generating a Random Number

5.7.1 Problem

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

5.7.2 Solution

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

5.7.3 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 by 10, divide by 10. This step converts the result to the correct number of decimal places.

6. Add the value from step 5 to the smallest value in the range. This offsets the value to be within the specified range.

A custom Math.randRange( ) method encapsulates the process so that you can generate random numbers while blissfully ignoring the details.

The custom randRange( ) method should take up to three parameters:

minNum

The smallest value in the range.

maxNum

The largest value in the range.

decPl

The number of decimal places to which to round the random number. If or omitted, the number is returned as an integer.

Here is our custom randRange( ) method, which is attached directly to the Math object, so it is available throughout the entire movie. It assumes that minNum is always less than maxNum. You can add this custom method to the Math.as file for easy inclusion in other projects.

```Math.randRange = function(minNum, maxNum, decPl) {

// Default to zero decimal places (generate a random integer).
decPl = (decPl == undefined) ? 0 : decPl;

// Calculate the range, multiply by 10 to the power of the number of decimal
// places, and add 1. We'll call this "delta".
var rangeDiff = (maxNum - minNum) * Math.pow(10, decPl) + 1;

// Multiplying delta by Math.random(  ) generates a value from 0 to 0.999 * delta.
var randVal = Math.random(  ) * rangeDiff;

// Truncate the value to the integer part.
randVal = Math.floor(randVal);

// Restore the proper number of decimal places.
randVal /= Math.pow(10, decPl);

// Add minNum as an offset to generate a random number in the correct range.
randVal += minNum;

// Return the random value. Use the custom roundTo(  ) method from Recipe 5.3 to
// ensure that the result is rounded to the proper number of decimal places.
return Math.roundTo(randVal, Math.pow(10, -decPl));
};```

Here is an example of how to use the randRange( ) method, assuming it has been stored in an external ActionScript text file named Math.as:

```#include "Math.as"

// Generate a random integer from 5 to 10, inclusive.
trace(Math.randRange(5, 10));

// Generate a random number, rounded to two decimal places from -5 to 5.
trace(Math.randRange(-5, 5, 2));```

You can use randRange( ) when you don't want an even distribution from 0 to the maximum value in the range. Here is an example of how to use randRange( ) to generate a random alpha value for a movie clip in the range of 75 to 100. It allows a clip to have a random alpha while avoiding clips that are too transparent.

`myMovieClip._alpha = Math.randRange(75, 100);`

Random numbers generated by traditional programming languages are not truly random. Rather, they are derived from a pseudorandom algorithm fed by an initial random seed. ActionScript does not allow you to specify the random seed (Flash presumably uses an essentially random starting point, such as the time in milliseconds). Don't confuse a random number with a unique number because random numbers are not guaranteed to be unique.

Recipe 5.3 and Recipe 5.11   Preface  Part I: Local Recipes  Chapter 1. ActionScript Basics  Chapter 2. Runtime Environment  Chapter 3. Color  Chapter 4. Drawing and Masking  Chapter 5. Numbers and Math  Introduction  Recipe 5.1 Representing Numbers in Different Bases  Recipe 5.2 Converting Between Different Number Systems  Recipe 5.3 Rounding Numbers  Recipe 5.4 Inserting Leading or Trailing Zeros  Recipe 5.5 Formatting Numbers for Display  Recipe 5.6 Formatting Currency Amounts  Recipe 5.7 Generating a Random Number  Recipe 5.8 Simulating a Coin Flip  Recipe 5.9 Simulating Dice  Recipe 5.10 Simulating Playing Cards  Recipe 5.11 Generating a Unique Number  Recipe 5.12 Converting Angle Measurements  Recipe 5.13 Calculating the Distance Between Two Points  Recipe 5.14 Determining Points Along a Circle  Recipe 5.15 Converting Between Units of Measurement  Recipe 5.16 Calculating Asset Appreciation (Future Value)  Recipe 5.17 Calculating Retirement Savings  Recipe 5.18 Calculating the Loan (Mortgage) You Can Afford  Recipe 5.19 Calculating Loan Amortization or Annuities  Chapter 6. Arrays  Chapter 7. Movie Clips  Chapter 8. Text  Chapter 9. Strings  Chapter 10. Dates and Times  Chapter 11. Forms  Chapter 12. Objects and Custom Components  Chapter 13. Programming Sound  Part II: Remote Recipes  Part III: Applications  Appendix A. Unicode Escape Sequences for Latin 1 Characters  Colophon