Random Behavior


Pseudo-Random?

The nextInt (or nextFloat or nextBoolean) method returns values that are:

Why do we care?

===>   It matters if you construct multiple Random objects (generators) to generate multiple random numbers, rather than using a single generator and just calling nextInt multiple times.

To illustrate this, consider a program that generates 10 different sequences of random numbers, each from a different random number generator. The pseudo-code for this program is:

    Create 10 random number generators (10 objects of the Random class)
    Create 10 lists, one for each generator
    Loop 20 times:
        Get an int from generator #1 and add to list #1
        Get an int from generator #2 and add to list #2
        Get an int from generator #3 and add to list #3
        Do the same for the other 7 generators

The first fifteen results from the first three generators from a particular run were:

    Generator #1: 2, 2, 2, 0, 0, 1, 2, 0, 0, 0, 1, 0, 0, 2, 0
    Generator #2: 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 2, 1
    Generator #3: 2, 2, 2, 0, 2, 2, 1, 0, 0, 2, 2, 1, 0, 1, 2

Comparing results of Generator #1 with Generator #3:

    Generator #1: 2, 2, 2, 0, 0, 1, 2, 0, 0, 0, 1, 0, 0, 2, 0
    Generator #3: 2, 2, 2, 0, 2, 2, 1, 0, 0, 2, 2, 1, 0, 1, 2
                  ^  ^  ^  ^           ^  ^           ^

Comparing results of Generator #1 with Generator #2, shifted:

    Generator #1: 2, 2, 2, 0, 0, 1, 2, 0, 0, 0, 1, 0, 0, 2, 0
    Generator #2:          0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1
                           ^  ^  ^     ^  ^  ^  ^     ^

Not all the generators created sequences that were so similar, and all the sequences became less similar as they got further into the sequence. It's clear, though, that multiple generators, when constructed close together in time, can generate sequences with strong similarities.

The moral of the story is:

Create just one Random number generator for your program or class, whenever you can.


Alyce Brady, Kalamazoo College