ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/Random.java
Revision: 1.1
Committed: Tue May 27 15:49:59 2003 UTC (21 years ago) by dl
Branch: MAIN
CVS Tags: JSR166_CR1, JSR166_PRELIMINARY_TEST_RELEASE_1, JSR166_PRELIMINARY_TEST_RELEASE_2, JSR166_PRERELEASE_0_1
Log Message:
Initial implementations

File Contents

# Content
1 /*
2 * @(#)Random.java 1.38 02/03/04
3 *
4 * Copyright 2002 Sun Microsystems, Inc. All rights reserved.
5 * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6 */
7
8 package java.util;
9 import java.io.*;
10 import sun.misc.Unsafe;
11
12 /**
13 * An instance of this class is used to generate a stream of
14 * pseudorandom numbers. The class uses a 48-bit seed, which is
15 * modified using a linear congruential formula. (See Donald Knuth,
16 * <i>The Art of Computer Programming, Volume 2</i>, Section 3.2.1.)
17 * <p>
18 * If two instances of <code>Random</code> are created with the same
19 * seed, and the same sequence of method calls is made for each, they
20 * will generate and return identical sequences of numbers. In order to
21 * guarantee this property, particular algorithms are specified for the
22 * class <tt>Random</tt>. Java implementations must use all the algorithms
23 * shown here for the class <tt>Random</tt>, for the sake of absolute
24 * portability of Java code. However, subclasses of class <tt>Random</tt>
25 * are permitted to use other algorithms, so long as they adhere to the
26 * general contracts for all the methods.
27 * <p>
28 * The algorithms implemented by class <tt>Random</tt> use a
29 * <tt>protected</tt> utility method that on each invocation can supply
30 * up to 32 pseudorandomly generated bits.
31 * <p>
32 * Many applications will find the <code>random</code> method in
33 * class <code>Math</code> simpler to use.
34 *
35 * @author Frank Yellin
36 * @version 1.38, 03/04/02
37 * @see java.lang.Math#random()
38 * @since JDK1.0
39 */
40 public
41 class Random implements java.io.Serializable {
42 /** use serialVersionUID from JDK 1.1 for interoperability */
43 static final long serialVersionUID = 3905348978240129619L;
44
45 // Setup to use Unsafe.compareAndSwapLong to update seed.
46 private static final Unsafe unsafe = Unsafe.getUnsafe();
47 private static final long seedOffset;
48 static {
49 try {
50 seedOffset =
51 unsafe.objectFieldOffset(Random.class.getDeclaredField("seed"));
52 }
53 catch(Exception ex) { throw new Error(ex); }
54 }
55
56 /**
57 * The internal state associated with this pseudorandom number generator.
58 * (The specs for the methods in this class describe the ongoing
59 * computation of this value.)
60 *
61 * @serial
62 */
63 private volatile long seed;
64
65 private final static long multiplier = 0x5DEECE66DL;
66 private final static long addend = 0xBL;
67 private final static long mask = (1L << 48) - 1;
68
69 /**
70 * Creates a new random number generator. Its seed is initialized to
71 * a value based on the current time:
72 * <blockquote><pre>
73 * public Random() { this(System.currentTimeMillis()); }</pre></blockquote>
74 * Two Random objects created within the same millisecond will have
75 * the same sequence of random numbers.
76 *
77 * @see java.lang.System#currentTimeMillis()
78 */
79 public Random() { this(System.currentTimeMillis()); }
80
81 /**
82 * Creates a new random number generator using a single
83 * <code>long</code> seed:
84 * <blockquote><pre>
85 * public Random(long seed) { setSeed(seed); }</pre></blockquote>
86 * Used by method <tt>next</tt> to hold
87 * the state of the pseudorandom number generator.
88 *
89 * @param seed the initial seed.
90 * @see java.util.Random#setSeed(long)
91 */
92 public Random(long seed) {
93 setSeed(seed);
94 }
95
96 /**
97 * Sets the seed of this random number generator using a single
98 * <code>long</code> seed. The general contract of <tt>setSeed</tt>
99 * is that it alters the state of this random number generator
100 * object so as to be in exactly the same state as if it had just
101 * been created with the argument <tt>seed</tt> as a seed. The method
102 * <tt>setSeed</tt> is implemented by class Random as follows:
103 * <blockquote><pre>
104 * synchronized public void setSeed(long seed) {
105 * this.seed = (seed ^ 0x5DEECE66DL) & ((1L << 48) - 1);
106 * haveNextNextGaussian = false;
107 * }</pre></blockquote>
108 * The implementation of <tt>setSeed</tt> by class <tt>Random</tt>
109 * happens to use only 48 bits of the given seed. In general, however,
110 * an overriding method may use all 64 bits of the long argument
111 * as a seed value.
112 *
113 * Note: Even though seed is updated atomically, this method
114 * must still be synchronized to ensure correct semantics
115 * of haveNextNextGaussian.
116 *
117 * @param seed the initial seed.
118 */
119 synchronized public void setSeed(long seed) {
120 this.seed = (seed ^ multiplier) & mask;
121 haveNextNextGaussian = false;
122 }
123
124 /**
125 * Generates the next pseudorandom number. Subclass should
126 * override this, as this is used by all other methods.<p>
127 * The general contract of <tt>next</tt> is that it returns an
128 * <tt>int</tt> value and if the argument bits is between <tt>1</tt>
129 * and <tt>32</tt> (inclusive), then that many low-order bits of the
130 * returned value will be (approximately) independently chosen bit
131 * values, each of which is (approximately) equally likely to be
132 * <tt>0</tt> or <tt>1</tt>. The method <tt>next</tt> is implemented
133 * by class <tt>Random</tt> as follows:
134 * <blockquote><pre>
135 * synchronized protected int next(int bits) {
136 * seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1);
137 * return (int)(seed >>> (48 - bits));
138 * }</pre></blockquote>
139 * This is a linear congruential pseudorandom number generator, as
140 * defined by D. H. Lehmer and described by Donald E. Knuth in <i>The
141 * Art of Computer Programming,</i> Volume 2: <i>Seminumerical
142 * Algorithms</i>, section 3.2.1.
143 *
144 * @param bits random bits
145 * @return the next pseudorandom value from this random number generator's sequence.
146 * @since JDK1.1
147 */
148 protected int next(int bits) {
149 long oldseed, nextseed;
150 do {
151 oldseed = seed;
152 nextseed = (oldseed * multiplier + addend) & mask;
153 } while (!unsafe.compareAndSwapLong(this, seedOffset,
154 oldseed, nextseed));
155 return (int)(nextseed >>> (48 - bits));
156 }
157
158 private static final int BITS_PER_BYTE = 8;
159 private static final int BYTES_PER_INT = 4;
160
161 /**
162 * Generates random bytes and places them into a user-supplied
163 * byte array. The number of random bytes produced is equal to
164 * the length of the byte array.
165 *
166 * @param bytes the non-null byte array in which to put the
167 * random bytes.
168 * @since JDK1.1
169 */
170 public void nextBytes(byte[] bytes) {
171 int numRequested = bytes.length;
172
173 int numGot = 0, rnd = 0;
174
175 while (true) {
176 for (int i = 0; i < BYTES_PER_INT; i++) {
177 if (numGot == numRequested)
178 return;
179
180 rnd = (i==0 ? next(BITS_PER_BYTE * BYTES_PER_INT)
181 : rnd >> BITS_PER_BYTE);
182 bytes[numGot++] = (byte)rnd;
183 }
184 }
185 }
186
187 /**
188 * Returns the next pseudorandom, uniformly distributed <code>int</code>
189 * value from this random number generator's sequence. The general
190 * contract of <tt>nextInt</tt> is that one <tt>int</tt> value is
191 * pseudorandomly generated and returned. All 2<font size="-1"><sup>32
192 * </sup></font> possible <tt>int</tt> values are produced with
193 * (approximately) equal probability. The method <tt>nextInt</tt> is
194 * implemented by class <tt>Random</tt> as follows:
195 * <blockquote><pre>
196 * public int nextInt() { return next(32); }</pre></blockquote>
197 *
198 * @return the next pseudorandom, uniformly distributed <code>int</code>
199 * value from this random number generator's sequence.
200 */
201 public int nextInt() { return next(32); }
202
203 /**
204 * Returns a pseudorandom, uniformly distributed <tt>int</tt> value
205 * between 0 (inclusive) and the specified value (exclusive), drawn from
206 * this random number generator's sequence. The general contract of
207 * <tt>nextInt</tt> is that one <tt>int</tt> value in the specified range
208 * is pseudorandomly generated and returned. All <tt>n</tt> possible
209 * <tt>int</tt> values are produced with (approximately) equal
210 * probability. The method <tt>nextInt(int n)</tt> is implemented by
211 * class <tt>Random</tt> as follows:
212 * <blockquote><pre>
213 * public int nextInt(int n) {
214 * if (n<=0)
215 * throw new IllegalArgumentException("n must be positive");
216 *
217 * if ((n & -n) == n) // i.e., n is a power of 2
218 * return (int)((n * (long)next(31)) >> 31);
219 *
220 * int bits, val;
221 * do {
222 * bits = next(31);
223 * val = bits % n;
224 * } while(bits - val + (n-1) < 0);
225 * return val;
226 * }
227 * </pre></blockquote>
228 * <p>
229 * The hedge "approximately" is used in the foregoing description only
230 * because the next method is only approximately an unbiased source of
231 * independently chosen bits. If it were a perfect source of randomly
232 * chosen bits, then the algorithm shown would choose <tt>int</tt>
233 * values from the stated range with perfect uniformity.
234 * <p>
235 * The algorithm is slightly tricky. It rejects values that would result
236 * in an uneven distribution (due to the fact that 2^31 is not divisible
237 * by n). The probability of a value being rejected depends on n. The
238 * worst case is n=2^30+1, for which the probability of a reject is 1/2,
239 * and the expected number of iterations before the loop terminates is 2.
240 * <p>
241 * The algorithm treats the case where n is a power of two specially: it
242 * returns the correct number of high-order bits from the underlying
243 * pseudo-random number generator. In the absence of special treatment,
244 * the correct number of <i>low-order</i> bits would be returned. Linear
245 * congruential pseudo-random number generators such as the one
246 * implemented by this class are known to have short periods in the
247 * sequence of values of their low-order bits. Thus, this special case
248 * greatly increases the length of the sequence of values returned by
249 * successive calls to this method if n is a small power of two.
250 *
251 * @param n the bound on the random number to be returned. Must be
252 * positive.
253 * @return a pseudorandom, uniformly distributed <tt>int</tt>
254 * value between 0 (inclusive) and n (exclusive).
255 * @exception IllegalArgumentException n is not positive.
256 * @since 1.2
257 */
258
259 public int nextInt(int n) {
260 if (n<=0)
261 throw new IllegalArgumentException("n must be positive");
262
263 if ((n & -n) == n) // i.e., n is a power of 2
264 return (int)((n * (long)next(31)) >> 31);
265
266 int bits, val;
267 do {
268 bits = next(31);
269 val = bits % n;
270 } while(bits - val + (n-1) < 0);
271 return val;
272 }
273
274 /**
275 * Returns the next pseudorandom, uniformly distributed <code>long</code>
276 * value from this random number generator's sequence. The general
277 * contract of <tt>nextLong</tt> is that one long value is pseudorandomly
278 * generated and returned. All 2<font size="-1"><sup>64</sup></font>
279 * possible <tt>long</tt> values are produced with (approximately) equal
280 * probability. The method <tt>nextLong</tt> is implemented by class
281 * <tt>Random</tt> as follows:
282 * <blockquote><pre>
283 * public long nextLong() {
284 * return ((long)next(32) << 32) + next(32);
285 * }</pre></blockquote>
286 *
287 * @return the next pseudorandom, uniformly distributed <code>long</code>
288 * value from this random number generator's sequence.
289 */
290 public long nextLong() {
291 // it's okay that the bottom word remains signed.
292 return ((long)(next(32)) << 32) + next(32);
293 }
294
295 /**
296 * Returns the next pseudorandom, uniformly distributed
297 * <code>boolean</code> value from this random number generator's
298 * sequence. The general contract of <tt>nextBoolean</tt> is that one
299 * <tt>boolean</tt> value is pseudorandomly generated and returned. The
300 * values <code>true</code> and <code>false</code> are produced with
301 * (approximately) equal probability. The method <tt>nextBoolean</tt> is
302 * implemented by class <tt>Random</tt> as follows:
303 * <blockquote><pre>
304 * public boolean nextBoolean() {return next(1) != 0;}
305 * </pre></blockquote>
306 * @return the next pseudorandom, uniformly distributed
307 * <code>boolean</code> value from this random number generator's
308 * sequence.
309 * @since 1.2
310 */
311 public boolean nextBoolean() {return next(1) != 0;}
312
313 /**
314 * Returns the next pseudorandom, uniformly distributed <code>float</code>
315 * value between <code>0.0</code> and <code>1.0</code> from this random
316 * number generator's sequence. <p>
317 * The general contract of <tt>nextFloat</tt> is that one <tt>float</tt>
318 * value, chosen (approximately) uniformly from the range <tt>0.0f</tt>
319 * (inclusive) to <tt>1.0f</tt> (exclusive), is pseudorandomly
320 * generated and returned. All 2<font size="-1"><sup>24</sup></font>
321 * possible <tt>float</tt> values of the form
322 * <i>m&nbsp;x&nbsp</i>2<font size="-1"><sup>-24</sup></font>, where
323 * <i>m</i> is a positive integer less than 2<font size="-1"><sup>24</sup>
324 * </font>, are produced with (approximately) equal probability. The
325 * method <tt>nextFloat</tt> is implemented by class <tt>Random</tt> as
326 * follows:
327 * <blockquote><pre>
328 * public float nextFloat() {
329 * return next(24) / ((float)(1 << 24));
330 * }</pre></blockquote>
331 * The hedge "approximately" is used in the foregoing description only
332 * because the next method is only approximately an unbiased source of
333 * independently chosen bits. If it were a perfect source or randomly
334 * chosen bits, then the algorithm shown would choose <tt>float</tt>
335 * values from the stated range with perfect uniformity.<p>
336 * [In early versions of Java, the result was incorrectly calculated as:
337 * <blockquote><pre>
338 * return next(30) / ((float)(1 << 30));</pre></blockquote>
339 * This might seem to be equivalent, if not better, but in fact it
340 * introduced a slight nonuniformity because of the bias in the rounding
341 * of floating-point numbers: it was slightly more likely that the
342 * low-order bit of the significand would be 0 than that it would be 1.]
343 *
344 * @return the next pseudorandom, uniformly distributed <code>float</code>
345 * value between <code>0.0</code> and <code>1.0</code> from this
346 * random number generator's sequence.
347 */
348 public float nextFloat() {
349 int i = next(24);
350 return i / ((float)(1 << 24));
351 }
352
353 /**
354 * Returns the next pseudorandom, uniformly distributed
355 * <code>double</code> value between <code>0.0</code> and
356 * <code>1.0</code> from this random number generator's sequence. <p>
357 * The general contract of <tt>nextDouble</tt> is that one
358 * <tt>double</tt> value, chosen (approximately) uniformly from the
359 * range <tt>0.0d</tt> (inclusive) to <tt>1.0d</tt> (exclusive), is
360 * pseudorandomly generated and returned. All
361 * 2<font size="-1"><sup>53</sup></font> possible <tt>float</tt>
362 * values of the form <i>m&nbsp;x&nbsp;</i>2<font size="-1"><sup>-53</sup>
363 * </font>, where <i>m</i> is a positive integer less than
364 * 2<font size="-1"><sup>53</sup></font>, are produced with
365 * (approximately) equal probability. The method <tt>nextDouble</tt> is
366 * implemented by class <tt>Random</tt> as follows:
367 * <blockquote><pre>
368 * public double nextDouble() {
369 * return (((long)next(26) << 27) + next(27))
370 * / (double)(1L << 53);
371 * }</pre></blockquote><p>
372 * The hedge "approximately" is used in the foregoing description only
373 * because the <tt>next</tt> method is only approximately an unbiased
374 * source of independently chosen bits. If it were a perfect source or
375 * randomly chosen bits, then the algorithm shown would choose
376 * <tt>double</tt> values from the stated range with perfect uniformity.
377 * <p>[In early versions of Java, the result was incorrectly calculated as:
378 * <blockquote><pre>
379 * return (((long)next(27) << 27) + next(27))
380 * / (double)(1L << 54);</pre></blockquote>
381 * This might seem to be equivalent, if not better, but in fact it
382 * introduced a large nonuniformity because of the bias in the rounding
383 * of floating-point numbers: it was three times as likely that the
384 * low-order bit of the significand would be 0 than that it would be
385 * 1! This nonuniformity probably doesn't matter much in practice, but
386 * we strive for perfection.]
387 *
388 * @return the next pseudorandom, uniformly distributed
389 * <code>double</code> value between <code>0.0</code> and
390 * <code>1.0</code> from this random number generator's sequence.
391 */
392 public double nextDouble() {
393 long l = ((long)(next(26)) << 27) + next(27);
394 return l / (double)(1L << 53);
395 }
396
397 private double nextNextGaussian;
398 private boolean haveNextNextGaussian = false;
399
400 /**
401 * Returns the next pseudorandom, Gaussian ("normally") distributed
402 * <code>double</code> value with mean <code>0.0</code> and standard
403 * deviation <code>1.0</code> from this random number generator's sequence.
404 * <p>
405 * The general contract of <tt>nextGaussian</tt> is that one
406 * <tt>double</tt> value, chosen from (approximately) the usual
407 * normal distribution with mean <tt>0.0</tt> and standard deviation
408 * <tt>1.0</tt>, is pseudorandomly generated and returned. The method
409 * <tt>nextGaussian</tt> is implemented by class <tt>Random</tt> as follows:
410 * <blockquote><pre>
411 * synchronized public double nextGaussian() {
412 * if (haveNextNextGaussian) {
413 * haveNextNextGaussian = false;
414 * return nextNextGaussian;
415 * } else {
416 * double v1, v2, s;
417 * do {
418 * v1 = 2 * nextDouble() - 1; // between -1.0 and 1.0
419 * v2 = 2 * nextDouble() - 1; // between -1.0 and 1.0
420 * s = v1 * v1 + v2 * v2;
421 * } while (s >= 1 || s == 0);
422 * double multiplier = Math.sqrt(-2 * Math.log(s)/s);
423 * nextNextGaussian = v2 * multiplier;
424 * haveNextNextGaussian = true;
425 * return v1 * multiplier;
426 * }
427 * }</pre></blockquote>
428 * This uses the <i>polar method</i> of G. E. P. Box, M. E. Muller, and
429 * G. Marsaglia, as described by Donald E. Knuth in <i>The Art of
430 * Computer Programming</i>, Volume 2: <i>Seminumerical Algorithms</i>,
431 * section 3.4.1, subsection C, algorithm P. Note that it generates two
432 * independent values at the cost of only one call to <tt>Math.log</tt>
433 * and one call to <tt>Math.sqrt</tt>.
434 *
435 * @return the next pseudorandom, Gaussian ("normally") distributed
436 * <code>double</code> value with mean <code>0.0</code> and
437 * standard deviation <code>1.0</code> from this random number
438 * generator's sequence.
439 */
440 synchronized public double nextGaussian() {
441 // See Knuth, ACP, Section 3.4.1 Algorithm C.
442 if (haveNextNextGaussian) {
443 haveNextNextGaussian = false;
444 return nextNextGaussian;
445 } else {
446 double v1, v2, s;
447 do {
448 v1 = 2 * nextDouble() - 1; // between -1 and 1
449 v2 = 2 * nextDouble() - 1; // between -1 and 1
450 s = v1 * v1 + v2 * v2;
451 } while (s >= 1 || s == 0);
452 double multiplier = Math.sqrt(-2 * Math.log(s)/s);
453 nextNextGaussian = v2 * multiplier;
454 haveNextNextGaussian = true;
455 return v1 * multiplier;
456 }
457 }
458
459 /**
460 * Serializable fields for Random.
461 *
462 * @serialField seed long;
463 * seed for random computations
464 * @serialField nextNextGaussian double;
465 * next Gaussian to be returned
466 * @serialField haveNextNextGaussian boolean
467 * nextNextGaussian is valid
468 */
469 private static final ObjectStreamField[] serialPersistentFields = {
470 new ObjectStreamField("seed", Long.TYPE),
471 new ObjectStreamField("nextNextGaussian", Double.TYPE),
472 new ObjectStreamField("haveNextNextGaussian", Boolean.TYPE)
473 };
474
475 /**
476 * Reconstitute the <tt>Random</tt> instance from a stream (that is,
477 * deserialize it). The seed is read in as long for
478 * historical reasons, but it is converted to an AtomicLong.
479 */
480 private void readObject(java.io.ObjectInputStream s)
481 throws java.io.IOException, ClassNotFoundException {
482
483 ObjectInputStream.GetField fields = s.readFields();
484 long seedVal;
485
486 seedVal = (long) fields.get("seed", -1L);
487 if (seedVal < 0)
488 throw new java.io.StreamCorruptedException(
489 "Random: invalid seed");
490 seed = seedVal;
491 nextNextGaussian = fields.get("nextNextGaussian", 0.0);
492 haveNextNextGaussian = fields.get("haveNextNextGaussian", false);
493 }
494
495
496 /**
497 * Save the <tt>Random</tt> instance to a stream.
498 * The seed of a Random is serialized as a long for
499 * historical reasons.
500 *
501 */
502 synchronized private void writeObject(ObjectOutputStream s) throws IOException {
503 // set the values of the Serializable fields
504 ObjectOutputStream.PutField fields = s.putFields();
505 fields.put("seed", seed);
506 fields.put("nextNextGaussian", nextNextGaussian);
507 fields.put("haveNextNextGaussian", haveNextNextGaussian);
508
509 // save them
510 s.writeFields();
511
512 }
513
514 }