• Create BookmarkCreate Bookmark
• Create Note or TagCreate Note or Tag
• PrintPrint

## Generating Pseudorandom Numbers

NN 2, IE 3

### Problem

You want to generate a random number.

### 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.

### 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.

PREVIEW

Not a subscriber?

Start A Free Trial

• Create BookmarkCreate Bookmark
• Create Note or TagCreate Note or Tag
• PrintPrint