ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/Random.java
Revision: 1.28
Committed: Mon Sep 27 19:15:15 2010 UTC (13 years, 7 months ago) by jsr166
Branch: MAIN
Changes since 1.27: +3 -3 lines
Log Message:
use blessed declaration modifier order

File Contents

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