Java Notes
Random numbers - Introduction
When to use random numbers
There are many types of programs that use random numbers. Game programs use them to create situations that are not always the same every time a player is in the same situation, or a deck of cards must be shuffled. Simulations usually use random numbers. You might want to use random numbers to change the appearance of something -- screensavers are an example of use. There are many other uses also.
Type, Range, and Distribution
When you generate random numbers, you need to decide which type you need (eg, int or double), what range you need (minimum to maximum), and how they are distributed. There are two common types of distributions: uniform and normal (equivalent to Gaussian). In a uniform distribution all numbers in the range are equally likely to be produced.
How can a computer generate a random number?
Computers are deterministic -- they do the same thing whenever they have the same input. Therefore, in some way it is impossible for a computer to compute a truly random number. But the methods that are used generate sequences of numbers that meet the statistical requirements of randomness. Because the numbers are not truly random, they are sometimes referred to as pseudorandom numbers. These random number generates will produce exactly the same sequence of pseudorandom numbers if they start with the same initial value. This initial value is called the seed.
If we start a program with the same random seed, we will get the same sequence of numbers. The default seed is the current time in milliseconds since 1970. This works very well, but you might want to set the seed so that the sequence can be reproduced when you are testing your program.
Related pages
- Random numbers - API
- Random Numbers - shuffling
- java.sun.com/docs/books/effective/excursion-random.html, Excursion 1: Random Thoughts by Joshua Bloch, author of Effective Java.