KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jgap > util > randomMCG


1 package org.jgap.util;
2
3
4 /**
5     Implementation of a <b>randomX</b>-compliant class using the
6     "Minimal Standard" multiplicative congruential generator of Park
7     and Miller. [Park, S.K. and K.W. Miller, <cite>Communications of
8     the ACM</cite> <b>31</b>, 1192-1201 (1988).]
9
10     <p>
11     The generation algorithm is:
12
13     <p>
14     <center>
15         <em>I<sub>j+1</sub></em> = (<em>I<sub>j</sub></em> 16807) & 0x7FFFFFFF
16     </center>
17
18     <p>
19     Note that the intermediate value of the multiplication by 16807
20     (7<sup>5</sup>) exceeds that representable in 32 bits; this has
21     deterred use of this generator in most portable languages.
22     Fortunately, Java's <tt>long</tt> type is guaranteed to be
23     64 bits, so a straightforward and portable implementation is
24     possible.
25
26     <p>
27     Designed and implemented in July 1996 by
28     <a HREF="http://www.fourmilab.ch/">John Walker</a>,
29     <a HREF="mailto:kelvin@fourmilab.ch">kelvin@fourmilab.ch</a>.
30 */

31 public class randomMCG extends randomX {
32     long state;
33
34     // Constructors
35

36     /** Creates a new pseudorandom number generator, seeded from
37         the current time. */

38
39     public randomMCG() {
40         this.setSeed(System.currentTimeMillis());
41     }
42
43     /** Creates a new pseudorandom number generator with a
44         specified nonzero seed.
45
46 @param seed initial seed for the generator
47     */

48
49     public randomMCG(long seed) throws IllegalArgumentException JavaDoc {
50         this.setSeed(seed);
51     }
52
53     // Seed access
54

55     /** Set seed for generator. Subsequent values will be based
56         on the given nonzero seed.
57
58 @param seed seed for the generator
59     */

60
61     public void setSeed(long seed) throws IllegalArgumentException JavaDoc {
62         int i;
63
64         if (seed == 0) {
65             throw new IllegalArgumentException JavaDoc("seed must be nonzero");
66         }
67         super.setSeed(); // Notify parent seed has changed
68
state = seed & 0xFFFFFFFFL;
69         for (i = 0; i < 11; i++) {
70             nextByte();
71         }
72     }
73
74     /** Get next byte from generator.
75
76 @return the next byte from the generator.
77     */

78
79     public byte nextByte() {
80         state = (state * 16807) & 0x7FFFFFFFL;
81         return (byte) ((state >> 11) & 0xFF);
82     }
83 };
84
Popular Tags