Wednesday 17 December 2014

How to Seed the Random Number Generator in Java

When you use a computer to produce random numbers, they are not really random in the way that tossing a coin or throwing a dice are. They are just a sequence of pseudo-random numbers generated by a function.

You can produce random numbers as shown in prog45 below. The random number generator then decides for itself where to start in the sequence so a different set of random numbers is produced each time you run the program:

andrew@UBUNTU:~/Java$ cat prog45.java
import java.util.Random;
public class prog45
{
public static void main (String args[])
 {
 Random random1 = new Random();
 System.out.println("Random number 1: "
 + random1.nextDouble());
 System.out.println("Random number 2: "
 + random1.nextDouble());
 }
}
andrew@UBUNTU:~/Java$ javac prog45.java
andrew@UBUNTU:~/Java$ java prog45
Random number 1: 0.9759678541914762
Random number 2: 0.03779439928385264
andrew@UBUNTU:~/Java$ java prog45
Random number 1: 0.16178369817427063
Random number 2: 0.6776376518531995
andrew@UBUNTU:~/Java$ java prog45
Random number 1: 0.9896967917912625
Random number 2: 0.2914450715965342
andrew@UBUNTU:~/Java$


Alternatively, you can seed the random number generator when you create a variable as shown in bold in prog46. This tells Java where to start in the sequence so it produces the same set of random numbers each time you run the program:

andrew@UBUNTU:~/Java$ cat prog46.java
import java.util.Random;
public class prog46
{
public static void main (String args[])
 {
 Random random1 = new Random(1);
 System.out.println("Random number 1: "
 + random1.nextDouble());
 System.out.println("Random number 2: "
 + random1.nextDouble());
 }
}
andrew@UBUNTU:~/Java$ javac prog46.java
andrew@UBUNTU:~/Java$ java prog46
Random number 1: 0.7308781907032909
Random number 2: 0.41008081149220166
andrew@UBUNTU:~/Java$ java prog46
Random number 1: 0.7308781907032909
Random number 2: 0.41008081149220166
andrew@UBUNTU:~/Java$


If you use a different number to seed the random number generator, you get a different series of random numbers:

andrew@UBUNTU:~/Java$ cat prog47.java
import java.util.Random;
public class prog47
{
public static void main (String args[])
 {
 Random random1 = new Random(999);
 System.out.println("Random number 1: "
 + random1.nextDouble());
 System.out.println("Random number 2: "
 + random1.nextDouble());
 }
}
andrew@UBUNTU:~/Java$ javac prog47.java
andrew@UBUNTU:~/Java$ java prog47
Random number 1: 0.7106328293942568
Random number 2: 0.7271143712820883
andrew@UBUNTU:~/Java$ java prog47
Random number 1: 0.7106328293942568
Random number 2: 0.7271143712820883
andrew@UBUNTU:~/Java
$