about


Scribe:

chrono

blog

Time

science!

book musings

gov

'punk

missle defense

jams

antiques

cultcha blog


Construct:

scripts & programs

on the town

snaps


Self:

creds (PDF)

key

missive


How to Create Random Numbers in JavaScript

The basic JavaScript random number generator creates a (pseudo-)random number somewhere between 0.0 up to (but not including) 1:

var randomNumber = Math.random()

0.6356236712055265
0.44685354164394475
0.08893780381545924
0.37436186623886725
In order to generate random numbers in a given range, you use Math.random to provide the seed. Then you set the range of random numbers you'd want by multiplying that number by one number beyond the upper limit of your desired range. For instance:

(Math.random() * 30)

would give you a random number that is somewhere between 0 and 29. You add an offset if you want the range to start somewhere other than 0:

(Math.random() * 30 + 5)

...has an offset of 5, so the random numbers being generated would range between 5 and 34.

To round a number to an integer, you could use any one of a number of math rounding agents (terminology mine): Math.floor, which rounds down to the next integer; Math.ceil, which rounds up; and Math.round, which rounds either up or down depending on what is the closet integer (7.5 rounds to 8, while -2.5 rounds to 2, for instance).

For the most uniform distribution, you would use Math.floor instead of Math.round. With Math.round, the first number and last number in your series would only have half as much of a chance of coming up as any of the other numbers in the series.

(Math.floor(5.787))

would return "5" for an answer.

Combining Math.Floor with Math.random paired with a range would go something like...

(Math.floor(Math.random() * 5))

would get something like this

0
4
0
3
4
4
3
...with random integers ranging from 0 to 4. Note that when you establish your range, you must use one number above the highest value in your range of possible random numbers, because of the rounding down, i.e. "(Math.floor((Math.random() * 30))" would give you a range of 0 to 29, not to 30.

Math.ceil could be instead of Math.floor, but make sure to adjust the range of desired numbers upward instead of downwards. In this case (Math.ceil((Math.random() * 30)) would give you an upper limit of 30, and a starting point of 1, not 0.

Here is an example of using random number generation to generate colors. Check the page source code to see how it works. .