The Java Course provides a general introduction to programming in Java. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.

# Array of Random Numbers

The first step is to generate a large number of random values and store them in an array. By "large number," of course, I mean 8. It's always a good idea to start with a manageable number, to help with debugging, and then increase it later.

The following method takes a single argument, the size of the array. It allocates a new array of doubles, fills it with random values, and returns a reference to the new array.

public static double[] randomArray (int n) {
double[] a = new double[n];
for (int i = 0; i<a.length; i++) {
a[i] = Math.random ();
}
return a;
}

The return type is double[], which means that this method returns an array of doubles. To test this method, it is convenient to have a method that prints the contents of an array.

public static void printArray (double[] a) {
for (int i = 0; i<a.length; i++) {
System.out.println (a[i]);
}
}

The following code generates an array and prints it:

int numValues = 8;
double[] array = randomArray (numValues);
printArray (array);

On my machine the output is

0.7344558779885422
0.6224282219647016
0.09591424515329172
0.2992298398883563
0.7736458103088713
0.7069110192991597
0.7042440765950522
0.977839532249852

which is pretty random-looking. Your results may differ.

If these numbers are really random, we expect half of them to be greater than 0.5 and half to be less. In fact, six are greater than 0.5, so that's a little high.

If we divide the range into four buckets---from 0.0 to 0.25, 0.25 to 0.5, 0.5 to 0.75, and 0.75 to 1.0---we expect 2 values to fall in each bucket. In fact, we get 1, 1, 4, 2. Again, not exactly what we expected.

Do these results mean the values are not really random? It's hard to tell. With so few values, the chances are slim that we would get exactly what we expect. But as the number of values increases, the outcome should be more predictable.

To test this theory, we'll write some programs that divide the range into buckets and count the number of values in each.

Last Update: 2011-01-24