ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jdk7/java/util/Random.java
Revision: 1.6
Committed: Sat Feb 7 23:29:18 2015 UTC (9 years, 1 month ago) by jsr166
Branch: MAIN
CVS Tags: HEAD
Changes since 1.5: +1 -1 lines
Log Message:
remedy copy-paste error of L'Ecuyer MLCG constant

File Contents

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