Random Generators

Of course, it's impossible for a computer to do anything that is truly random. By its very nature a computer is repeatable in everything that it does. Random number generators on a computer work essentially by performing a calculation so complicated that the result cannot be predicted from the input. A well-designed random number generator can produce a sequence of numbers that are evenly distributed through the possible range and indistinguishable from, say, rolling a dice or flipping a coin.

1. Creating and using random number generators

Getting random numbers involves two steps. First, you create a generator, an object that produces random numbers, telling it what range of numbers it should supply. Then, you ask that generator for its next value whenever you need a new random number.

There are two types of random number generators: one for ints and one for doubles:

public RandomIntGenerator(int min, int max)
public RandomDoubleGenerator(double min, double max)

A generator created in this way will then be able to produce numbers just in that range, where the smallest number it can produce is min and the largest is max. So, if I wanted to make a random number generator to simulate a typical six-sided die, I would do this:

RandomIntGenerator die = new RandomNumberGenerator(1, 6);

Both generators have a method nextValue() that returns the next value from the generator. This of course returns an int or a double depending on the type of the generator. If I wanted to roll two dice and add up the sum, I could do this:

int sum die.nextValue() + die.nextValue();