# 2.7 Generating Pseudorandom Numbers

NN 2, IE 3

#### 2.7.1 Problem

You want to generate a random number.

#### 2.7.2 Solution

The Math.random( ) method returns a pseudorandom number between 0 and 1. To calculate a pseudorandom integer value within a range starting with zero, use the formula:

`var result = Math.floor(Math.random( ) * (n + 1);`

where n is the highest acceptable integer of the range. To calculate a pseudorandom integer number within a range starting at a number other than zero, use the formula:

`var result = Math.floor(Math.random( ) * (n - m + 1)) + m;`

where m is the lowest acceptable integer of the range, and n is the highest acceptable integer of the range.

#### 2.7.3 Discussion

The previous examples focus on random integers, such as the kind you might use for values of a game cube (a die with numbers from 1 through 6). But you can remove the Math.floor( ) call to let the rest of the expression create random numbers with decimal fractions if you need them.

JavaScript's random number generator does not provide a mechanism for adjusting the seed to assure more genuine randomness. Thus, at best you can treat it as a pseudorandom number generator.

Section 2.0.2 in the introduction of this chapter.  Chapter 1. Strings  Chapter 2. Numbers and Dates  2.0 Introduction  2.1 Converting Between Numbers and Strings  2.2 Testing a Number's Validity  2.3 Testing Numeric Equality  2.4 Rounding Floating-Point Numbers  2.5 Formatting Numbers for Text Display  2.6 Converting Between Decimal and Hexadecimal Numbers  2.7 Generating Pseudorandom Numbers  2.8 Calculating Trigonometric Functions  2.9 Creating a Date Object  2.10 Calculating a Previous or Future Date  2.11 Calculating the Number of Days Between Two Dates  2.12 Validating a Date  Chapter 3. Arrays and Objects  Chapter 4. Variables, Functions, and Flow Control  Chapter 5. Browser Feature Detection  Chapter 6. Managing Browser Windows  Chapter 7. Managing Multiple Frames  Chapter 8. Dynamic Forms  Chapter 9. Managing Events  Chapter 10. Page Navigation Techniques  Chapter 11. Managing Style Sheets  Chapter 12. Visual Effects for Stationary Content  Chapter 13. Positioning HTML Elements  Chapter 14. Creating Dynamic Content  Chapter 15. Dynamic Content Applications  Appendix A. Keyboard Event Character Values  Appendix B. Keyboard Key Code Values  Appendix C. ECMAScript Reserved Keywords