Random Number Generator Methods


There are two ways to generate pseudorandom numbers in Java. The first way is using the random() function defined in the Math and StrictMath classes.


 public  static  double  random()

The random() method returns a positive double value between 0.0 and 1.0. The numbers generated are psuedorandom in that they are actually a set sequence of numbers. The starting point in the sequence is dictated by a seed that by default is set to the current time in milliseconds .

The second way to generate pseudorandom numbers is to use the Random class from the java.util package. With the Random class you can use a long value as the initial seed to make the number sequence more random. With the Random class you can pick your own seed value. You don't have to accept the current time in milliseconds as the seed. The Math.random() method is implemented in such a way that it simply calls the default Random class constructor.

Example: Using Random Number Generators

The RandomDemo class demonstrates two ways of creating a pseudorandom number sequence. The random() method will create a random number sequence using the current time in milliseconds as the seed. If a Random object is used, you can specify a different seed value. Two random number sequences that start with the same seed will produce the same sequence of numbers.

 import java.util.Random; public class RandomDemo {   public static void main(String args[]) {     //  Generating a psuedorandom number using the     //  random() method.     double value1 = Math.random();     System.out.println("value1 = "+value1);     //  Generating a psuedorandom number using a     //  Random object.  The Random object is seeded     //  with the current time in milliseconds + 1000     //  to produce a more random number.     try {       Thread.sleep(500);     } catch (InterruptedException ie ) {}     long seed = System.currentTimeMillis()+1000L;     Random rand = new Random(seed);     double value2 = rand.nextDouble();     System.out.println("value2 = "+value2);   } } 

Output (will vary) ”

 value1 = 0.4126443695 value2 = 0.7111293714 


Technical Java. Applications for Science and Engineering
Technical Java: Applications for Science and Engineering
ISBN: 0131018159
EAN: 2147483647
Year: 2003
Pages: 281
Authors: Grant Palmer

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