Abstract: A short introduction to the use of random numbers in JavaScript, with a pointer to some appropriate code.
When writing interactive programs, we often need to select "randomly" between a number of objects. Unfortunately, there is no algorithmic way to select truly randomly between objects. Usually, we use so-called pseudo-random number generators, which generate a random-seeming sequence of numbers.
Most random number generators must be "seeded" with an initial value (not the initial value they return, just some value) before they can produce a sequence of numbers. An advantage of being able to use seeds is that you can produce a reproducible random sequence, which is important for testing and debugging.
Typical random number generators return real number values between 0 and 1. By doing some simple math, we can easily turn those into integers between 1 and N (which is a typical way of using random numbers), as in
/ Function // randomInRange(N) // Description // Returns a "random" number between 1 and N function randomInRange(N) { return 1 + Math.floor(N*randomFraction()) } // randomInRange
I've included a library, random.js that provides three
basic functions,
randomInRange(N), which returns a "random" number
between 1 and N
randomFraction(), which returns a "random" number
between 0 and 1
seedRandom(seed), which allows you to seed the random
number generator
The library is based upon a random number generator developed by David N. Smith of IBM T.J. Watson laboratories.
There are a number of very bad random number generators out there. In particular, be suspicious of any random number generator that does not have some facility for being seeded (it's okay if it automatically seeds itself). I've seen some so-called random number generators that just do a fancy calculation with the current time of day. Such generators are likely to produce a fairly regular sequence (and, if they don't use milliseconds, may often return the same value multiple times in sequence).
Exercise: A simple math quiz.
This page written by Samuel A. Rebelsky.
This page generated on 46 by SamR's Site Suite.