Generating Random Numbers

   

Generating Random Numbers

The java.util.Random class provides a pseudorandom number generator that is more flexible than the one in the Math class. Actually, the random number generator in the Math class just uses one of the methods in the Random class to produce its results. Because the methods in the Random class are not static, you must create an instance of Random to use it. You can do this with the no-argument constructor or the one that accepts a seed:

 public Random() public Random(long seed) 

Note

"Random" numbers generated by a mathematical algorithm are not truly random, but are instead well-distributed values taken from a sequence that is defined by the algorithm. This distinction is why java.util.Random is described as a pseudorandom number generator.


If you define the seed for an instance of Random, you can duplicate a series of random numbers by using the same seed at a later time. The capability to generate the same series of numbers might not be useful for writing games or some other application that relies on randomness across executions, but it is useful when writing simulations where you want to replay the same sequences repeatedly. The no-argument constructor uses System.currentTimeMillis to seed the random number generator.

You can change the seed of the random number generator at any time using the setSeed method:

 public synchronized void setSeed(long newSeed) 

The Random class can generate random numbers in five different data types:

  • public int nextInt() ” Generates a 32-bit random number that can be any legal int value.

  • public long nextLong() ” Generates a 64-bit random number that can be any legal long value.

  • public float nextFloat() ” Generates a random float value between 0.0 and 1.0, although always less than 1.0.

  • public double nextDouble() ” Generates a random double value between 0.0 and 1.0, always less than 1.0. This is the method used by the Math.random method.

  • public boolean nextBoolean() ” Generates a boolean value of either true or false with equal probability.

There is also a special variation of random number that has some interesting mathematical properties. This variation is called nextGaussian, as declared in the following line:

 public synchronized double nextGaussian() 

This method returns a random double value that can be any legal double value. The mean (average) of the values generated by this method is 0.0, and the standard deviation is 1.0. This means that the numbers generated by this method are usually close to zero and that very large numbers are possible but rare.

   


Special Edition Using Java 2 Standard Edition
Special Edition Using Java 2, Standard Edition (Special Edition Using...)
ISBN: 0789724685
EAN: 2147483647
Year: 1999
Pages: 353

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net