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