More random generators

If we need a sequence of pseudo-random numbers in Java we could use the java.util.Random class. For simple requirements this would suffice, but when the game gets tougher it should be worthy have a look at the generators provided by the Apache Commons Math library.

If we want to fill up an array of integer with a random sequence of one digit numbers, we could write:
Random rg = new Random();
rg.setSeed(System.currentTimeMillis()); // 1

for (int i = 0; i < ia.length; ++i) // 2
    ia[i] = rg.nextInt(10); // 3
1. The generator is initialized using the current timestamp. 2. "ia" is an array of integer, supposed to be properly initialized. 3. Each element in the array is set to a random number extracted from the interval [0,9]. For testing purpose it is useful to generate always the same sequence, to do that we can rewrite (1) to set the seed to a constant value:
Apache Commons Math makes available a wrapper class that makes handier working with the standard random generator, letting us to easily change the generator to more advanced ones - provided by the library itself or created by ourselves.
RandomData rd = new RandomDataImpl(); // 1
for (int i = 0; i < ia.length; ++i) {
    ia[i] = rd.nextInt(0, 9); // 2
1. The current time is used to seed the generator, if we want to force using a specific seed we should call RandomDataImpl.reSeed(). Unfortunately this method is not part of the RandomData interface, so if we want this functionality be available we are forced to work with the concrete type. 2. Here nextInt() is more flexible, we specify both limit of the interval of values generated (besides, here the last one is included, in the java.util.Random it is excluded). Moreover, this method throws an exception if the second parameter is not bigger than the first one. One last notation, there is no check on the positiveness of the passed parameters (the standard Random throws a IllegalArgumentException if we pass a negative value), but the algorithm is not expected to works correctly for negative values. If we write the code using the Apache wrapper class, we can easily swap the random generator, using an overload of the constructor. So, to use the generator based on the Mersenne Twister instead of the JDK standard, we just have to rewrite (1) in this way:
RandomData rd = new RandomDataImpl(new MersenneTwister());
The Mersenne twister is one of the handful of generator based on the WELL family provided out of the (Apache) box.

No comments:

Post a Comment