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