Game Development Reference
In-Depth Information
The Gaussian distribution—the most commonly used probability function
Other probability functions
Monte Carlo simulations and how they can be used to simulate the behavior of large
systems
How Monte Carlo simulations can be used to simulate crowd behavior
Using Monte Carlo techniques to compute mathematical functions
Let's start the discussion with a brief overview of random number generation.
Random Number Generation
One thing that most Monte Carlo and probabilistic simulations (and many other game program-
ming applications as well) need is a way to generate random numbers. Fortunately, every modern
programming language provides a way to generate them. The examples in this topic are written
in Java, so we will discuss a little bit how the Java language supports random number genera-
tion. Most other languages use a similar approach to generating random numbers.
Java actually provides several ways to generate random numbers. The most versatile
approach, and the one used for the examples in this chapter, makes use of the Random class
from the java.util package. The Random class can provide the random numbers as integer,
floating-point, or byte numbers. The range over which the random numbers are generated
can also be specified.
Like most programming languages, random numbers generated by the Random class aren't
truly random. Instead, the Random class uses what is called a linear congruential algorithm to
generate a sequence of “pseudo” random numbers. Don't worry about the details of the linear
congruential algorithm; the important point is that the sequence of numbers generated by the
algorithm is deterministic, meaning that if the sequence is entered at the same starting point,
known as the seed , the subsequent series of numbers in the sequence will be the same.
The key to getting a different sequence of random numbers every time is to provide the
Random object with a different starting point, or seed, every time it is used. The Java language
provides for this feature automatically. When a Random object is created using the default
constructor:
Random randomObject = new Random();
the resulting Random object is given a seed equal to the number of milliseconds that have elapsed
since January 1, 1970 (no kidding!). As long as the Random objects are created at different times,
they will have different seeds and will generate different sequences of random numbers.
Let's write a short program that demonstrates the Random class in action. The class is called
RandomDemo , and its code listing is shown next. The nextDouble method is called on the Random
object to return a double precision floating-point number between 0 and 1.
import java.util.Random;
public class RandomDemo
{
public static void main(String args[]) {
Search WWH ::




Custom Search