Guest Author - Julie L Baumler
Random numbers have all sorts of uses, from the fun to the practical. Most games involve some sort of randomness in the form of things like dice or shuffled cards. If you want to display a random quote when someone visits your page, you need a source of randomness. Random numbers aren't all fun and games, random numbers are used in cryptography, for random sampling, for modeling, and for putting things in random order (such as candidates on a ballot.) Some of these uses don't use numbers directly, but you can convert from random numbers to random things by putting the things you want to choose in rows and randomly picking a row. In programming, arrays work well for this. Random numbers aren't always truly random. If you roll a set of fair dice, you will get random numbers, however the methods that computers use to pick random numbers are often pseudo-random numbers, meaning that they appear to be random on the surface but they are actually either predictable or a repeating series. For some things, this isn't an important difference. If you are displaying a random quote or joke each time someone loads your web page, it probably doesn't matter someone can predict when a specific quote will show up and you can safely use pseudo-random numbers (for that matter, you could probably just show your quotes in the order you happened to write them down.) If you are trying to do random drug testing of Tour de France athletes, it is crucial that athletes not be able to predict when or whether they will be tested.
To find a random number between 0 and (X-1), use:
Math.floor((Math.random() % 1) * X)
These are particularly useful for finding a random array element.
To find a random number between 1 and X, use:
Math.ceiling((Math.random() % 1) * X)
Tasks like this that are fairly common but require quite a bit of typing are good candidates for being turned into a function.
For a discussion of the difference between truly random numbers and the pseudo-random numbers we are using here, a source of truly random numbers, and some examples of fun things you can do with random or pseudo-random numbers check out www.random.org