ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/Random.java
Revision: 1.21
Committed: Sun May 18 23:47:56 2008 UTC (16 years ago) by jsr166
Branch: MAIN
Changes since 1.20: +29 -29 lines
Log Message:
Sync with OpenJDK; untabify

File Contents

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