Example: Mersenne Twister Random Number Generation

In this example, four simulation streams are generated. The first series is generated with the seed used for initialization. The second series is generated using an array for initialization. The third series is obtained by resetting the generator back to the state it had at the beginning of the second stream. Therefore, the second and third streams are identical. The fourth stream is obtained by resetting the generator back to its original, uninitialized state, and having it reinitialize using the seed. The first and fourth streams are therefore the same.

import com.imsl.stat.*;
import java.io.*;

public class MersenneTwister64Ex1 {

    public static void main(String args[]) throws Exception {
        long key[] = {0x123L, 0x234L, 0x345L, 0x456L};

        int nr = 4;
        double[] r = new double[nr];
        long s = 123457;
        /* Initialize MersenneTwister64 with a seed */
        MersenneTwister64 mt1 = new MersenneTwister64(s);
        MersenneTwister64 mt2 = (MersenneTwister64) mt1.clone();
        /* Save the state of MersenneTwister64 */
        FileOutputStream fos = new FileOutputStream("mt");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(mt1);
        oos.close();
        fos.close();
        Random rndm = new Random(mt1);

        /* Get the next five random numbers */
        for (int k = 0; k < nr; k++) {
            r[k] = rndm.nextDouble();
        }

        System.out.println("              First Stream Output");
        System.out.println(r[0] + "     " + r[1] + "     " + r[2]
                + "     " + r[3]);

        /* Check the cloned copy against the original */
        Random rndm2 = new Random(mt2);
        for (int k = 0; k < nr; k++) {
            r[k] = rndm2.nextDouble();
        }

        System.out.println("\n              Clone Stream Output");
        System.out.println(+r[0] + "     " + r[1] + "     " + r[2]
                + "     " + r[3]);

        /* Check the serialized copy against the original */
        FileInputStream fis = new FileInputStream("mt");
        ObjectInputStream ois = new ObjectInputStream(fis);
        mt2 = (MersenneTwister64) ois.readObject();
        Random rndm3 = new Random(mt2);
        for (int k = 0; k < nr; k++) {
            r[k] = rndm3.nextDouble();
        }
        System.out.println("\n              Serialized Stream Output");
        System.out.println(r[0] + "     " + r[1] + "     " + r[2]
                + "     " + r[3]);
    }
}

Output

              First Stream Output
0.5799165508168153     0.7101593787073387     0.5456686378667656     0.516359030432273

              Clone Stream Output
0.5799165508168153     0.7101593787073387     0.5456686378667656     0.516359030432273

              Serialized Stream Output
0.5799165508168153     0.7101593787073387     0.5456686378667656     0.516359030432273
Link to Java source.