ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jdk7/java/util/Random.java
Revision: 1.3
Committed: Sat Feb 16 20:50:29 2013 UTC (11 years, 3 months ago) by jsr166
Branch: MAIN
Changes since 1.2: +0 -1 lines
Log Message:
javadoc comment correctness

File Contents

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