KickJava   Java API By Example, From Geeks To Geeks.

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


1 package org.jgap.util;
2
3 /**
4     Implementation of a <b>randomX</b>-compliant class using the
5     simple (and not very good) <tt>rand()</tt> linear congruential
6     generator given as an example in the ANSI C specification. This
7     is intended not for serious use, merely as an illustration of a
8     simple software-based <b>randomX</b> generator.
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> × 1103515245 + 12345) & 0x7FFFFFFF
16     </center>
17
18     <p>
19     Designed and implemented in July 1996 by
20     <a HREF="http://www.fourmilab.ch/">John Walker</a>,
21     <a HREF="mailto:kelvin@fourmilab.ch">kelvin@fourmilab.ch</a>.
22 */

23 public class randomLCG extends randomX {
24     long state;
25
26     // Constructors
27

28     /** Creates a new pseudorandom number generator, seeded from
29         the current time. */

30
31     public randomLCG() {
32         this.setSeed(System.currentTimeMillis());
33     }
34
35     /** Creates a new pseudorandom number generator with a
36         specified seed.
37
38 @param seed initial seed for the generator
39     */

40
41     public randomLCG(long seed) {
42         this.setSeed(seed);
43     }
44
45     // Seed access
46

47     /** Set seed for generator. Subsequent values will be based
48         on the given seed.
49
50 @param seed seed for the generator
51     */

52
53     public void setSeed(long seed) {
54         super.setSeed(); // Notify parent seed has changed
55
state = seed & 0xFFFFFFFFL;
56     }
57
58     /** Get next byte from generator. Given how poor this generator
59         is, it's wise to make a separate call for each byte rather than
60         extract fields from a single call, which may be correlated.
61         Also, the higher-order bits of this generator are more
62         random than the low, so we extract the byte after discarding
63         the low-order 11 bits.
64
65 @return the next byte from the generator.
66     */

67
68     public byte nextByte() {
69         state = (state * 1103515245L + 12345L) & 0x7FFFFFFFL;
70         return (byte) ((state >> 11) & 0xFF);
71     }
72 };
73
Popular Tags