emul/compact/src/main/java/java/util/Random.java
branchjdk7-b147
changeset 597 ee8a922f4268
child 599 d0f57d3ea898
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/emul/compact/src/main/java/java/util/Random.java	Mon Jan 28 13:28:02 2013 +0100
     1.3 @@ -0,0 +1,575 @@
     1.4 +/*
     1.5 + * Copyright (c) 1995, 2010, Oracle and/or its affiliates. All rights reserved.
     1.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     1.7 + *
     1.8 + * This code is free software; you can redistribute it and/or modify it
     1.9 + * under the terms of the GNU General Public License version 2 only, as
    1.10 + * published by the Free Software Foundation.  Oracle designates this
    1.11 + * particular file as subject to the "Classpath" exception as provided
    1.12 + * by Oracle in the LICENSE file that accompanied this code.
    1.13 + *
    1.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
    1.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    1.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    1.17 + * version 2 for more details (a copy is included in the LICENSE file that
    1.18 + * accompanied this code).
    1.19 + *
    1.20 + * You should have received a copy of the GNU General Public License version
    1.21 + * 2 along with this work; if not, write to the Free Software Foundation,
    1.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    1.23 + *
    1.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    1.25 + * or visit www.oracle.com if you need additional information or have any
    1.26 + * questions.
    1.27 + */
    1.28 +
    1.29 +package java.util;
    1.30 +import java.io.*;
    1.31 +import java.util.concurrent.atomic.AtomicLong;
    1.32 +import sun.misc.Unsafe;
    1.33 +
    1.34 +/**
    1.35 + * An instance of this class is used to generate a stream of
    1.36 + * pseudorandom numbers. The class uses a 48-bit seed, which is
    1.37 + * modified using a linear congruential formula. (See Donald Knuth,
    1.38 + * <i>The Art of Computer Programming, Volume 2</i>, Section 3.2.1.)
    1.39 + * <p>
    1.40 + * If two instances of {@code Random} are created with the same
    1.41 + * seed, and the same sequence of method calls is made for each, they
    1.42 + * will generate and return identical sequences of numbers. In order to
    1.43 + * guarantee this property, particular algorithms are specified for the
    1.44 + * class {@code Random}. Java implementations must use all the algorithms
    1.45 + * shown here for the class {@code Random}, for the sake of absolute
    1.46 + * portability of Java code. However, subclasses of class {@code Random}
    1.47 + * are permitted to use other algorithms, so long as they adhere to the
    1.48 + * general contracts for all the methods.
    1.49 + * <p>
    1.50 + * The algorithms implemented by class {@code Random} use a
    1.51 + * {@code protected} utility method that on each invocation can supply
    1.52 + * up to 32 pseudorandomly generated bits.
    1.53 + * <p>
    1.54 + * Many applications will find the method {@link Math#random} simpler to use.
    1.55 + *
    1.56 + * <p>Instances of {@code java.util.Random} are threadsafe.
    1.57 + * However, the concurrent use of the same {@code java.util.Random}
    1.58 + * instance across threads may encounter contention and consequent
    1.59 + * poor performance. Consider instead using
    1.60 + * {@link java.util.concurrent.ThreadLocalRandom} in multithreaded
    1.61 + * designs.
    1.62 + *
    1.63 + * <p>Instances of {@code java.util.Random} are not cryptographically
    1.64 + * secure.  Consider instead using {@link java.security.SecureRandom} to
    1.65 + * get a cryptographically secure pseudo-random number generator for use
    1.66 + * by security-sensitive applications.
    1.67 + *
    1.68 + * @author  Frank Yellin
    1.69 + * @since   1.0
    1.70 + */
    1.71 +public
    1.72 +class Random implements java.io.Serializable {
    1.73 +    /** use serialVersionUID from JDK 1.1 for interoperability */
    1.74 +    static final long serialVersionUID = 3905348978240129619L;
    1.75 +
    1.76 +    /**
    1.77 +     * The internal state associated with this pseudorandom number generator.
    1.78 +     * (The specs for the methods in this class describe the ongoing
    1.79 +     * computation of this value.)
    1.80 +     */
    1.81 +    private final AtomicLong seed;
    1.82 +
    1.83 +    private static final long multiplier = 0x5DEECE66DL;
    1.84 +    private static final long addend = 0xBL;
    1.85 +    private static final long mask = (1L << 48) - 1;
    1.86 +
    1.87 +    /**
    1.88 +     * Creates a new random number generator. This constructor sets
    1.89 +     * the seed of the random number generator to a value very likely
    1.90 +     * to be distinct from any other invocation of this constructor.
    1.91 +     */
    1.92 +    public Random() {
    1.93 +        this(seedUniquifier() ^ System.nanoTime());
    1.94 +    }
    1.95 +
    1.96 +    private static long seedUniquifier() {
    1.97 +        // L'Ecuyer, "Tables of Linear Congruential Generators of
    1.98 +        // Different Sizes and Good Lattice Structure", 1999
    1.99 +        for (;;) {
   1.100 +            long current = seedUniquifier.get();
   1.101 +            long next = current * 181783497276652981L;
   1.102 +            if (seedUniquifier.compareAndSet(current, next))
   1.103 +                return next;
   1.104 +        }
   1.105 +    }
   1.106 +
   1.107 +    private static final AtomicLong seedUniquifier
   1.108 +        = new AtomicLong(8682522807148012L);
   1.109 +
   1.110 +    /**
   1.111 +     * Creates a new random number generator using a single {@code long} seed.
   1.112 +     * The seed is the initial value of the internal state of the pseudorandom
   1.113 +     * number generator which is maintained by method {@link #next}.
   1.114 +     *
   1.115 +     * <p>The invocation {@code new Random(seed)} is equivalent to:
   1.116 +     *  <pre> {@code
   1.117 +     * Random rnd = new Random();
   1.118 +     * rnd.setSeed(seed);}</pre>
   1.119 +     *
   1.120 +     * @param seed the initial seed
   1.121 +     * @see   #setSeed(long)
   1.122 +     */
   1.123 +    public Random(long seed) {
   1.124 +        this.seed = new AtomicLong(initialScramble(seed));
   1.125 +    }
   1.126 +
   1.127 +    private static long initialScramble(long seed) {
   1.128 +        return (seed ^ multiplier) & mask;
   1.129 +    }
   1.130 +
   1.131 +    /**
   1.132 +     * Sets the seed of this random number generator using a single
   1.133 +     * {@code long} seed. The general contract of {@code setSeed} is
   1.134 +     * that it alters the state of this random number generator object
   1.135 +     * so as to be in exactly the same state as if it had just been
   1.136 +     * created with the argument {@code seed} as a seed. The method
   1.137 +     * {@code setSeed} is implemented by class {@code Random} by
   1.138 +     * atomically updating the seed to
   1.139 +     *  <pre>{@code (seed ^ 0x5DEECE66DL) & ((1L << 48) - 1)}</pre>
   1.140 +     * and clearing the {@code haveNextNextGaussian} flag used by {@link
   1.141 +     * #nextGaussian}.
   1.142 +     *
   1.143 +     * <p>The implementation of {@code setSeed} by class {@code Random}
   1.144 +     * happens to use only 48 bits of the given seed. In general, however,
   1.145 +     * an overriding method may use all 64 bits of the {@code long}
   1.146 +     * argument as a seed value.
   1.147 +     *
   1.148 +     * @param seed the initial seed
   1.149 +     */
   1.150 +    synchronized public void setSeed(long seed) {
   1.151 +        this.seed.set(initialScramble(seed));
   1.152 +        haveNextNextGaussian = false;
   1.153 +    }
   1.154 +
   1.155 +    /**
   1.156 +     * Generates the next pseudorandom number. Subclasses should
   1.157 +     * override this, as this is used by all other methods.
   1.158 +     *
   1.159 +     * <p>The general contract of {@code next} is that it returns an
   1.160 +     * {@code int} value and if the argument {@code bits} is between
   1.161 +     * {@code 1} and {@code 32} (inclusive), then that many low-order
   1.162 +     * bits of the returned value will be (approximately) independently
   1.163 +     * chosen bit values, each of which is (approximately) equally
   1.164 +     * likely to be {@code 0} or {@code 1}. The method {@code next} is
   1.165 +     * implemented by class {@code Random} by atomically updating the seed to
   1.166 +     *  <pre>{@code (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1)}</pre>
   1.167 +     * and returning
   1.168 +     *  <pre>{@code (int)(seed >>> (48 - bits))}.</pre>
   1.169 +     *
   1.170 +     * This is a linear congruential pseudorandom number generator, as
   1.171 +     * defined by D. H. Lehmer and described by Donald E. Knuth in
   1.172 +     * <i>The Art of Computer Programming,</i> Volume 3:
   1.173 +     * <i>Seminumerical Algorithms</i>, section 3.2.1.
   1.174 +     *
   1.175 +     * @param  bits random bits
   1.176 +     * @return the next pseudorandom value from this random number
   1.177 +     *         generator's sequence
   1.178 +     * @since  1.1
   1.179 +     */
   1.180 +    protected int next(int bits) {
   1.181 +        long oldseed, nextseed;
   1.182 +        AtomicLong seed = this.seed;
   1.183 +        do {
   1.184 +            oldseed = seed.get();
   1.185 +            nextseed = (oldseed * multiplier + addend) & mask;
   1.186 +        } while (!seed.compareAndSet(oldseed, nextseed));
   1.187 +        return (int)(nextseed >>> (48 - bits));
   1.188 +    }
   1.189 +
   1.190 +    /**
   1.191 +     * Generates random bytes and places them into a user-supplied
   1.192 +     * byte array.  The number of random bytes produced is equal to
   1.193 +     * the length of the byte array.
   1.194 +     *
   1.195 +     * <p>The method {@code nextBytes} is implemented by class {@code Random}
   1.196 +     * as if by:
   1.197 +     *  <pre> {@code
   1.198 +     * public void nextBytes(byte[] bytes) {
   1.199 +     *   for (int i = 0; i < bytes.length; )
   1.200 +     *     for (int rnd = nextInt(), n = Math.min(bytes.length - i, 4);
   1.201 +     *          n-- > 0; rnd >>= 8)
   1.202 +     *       bytes[i++] = (byte)rnd;
   1.203 +     * }}</pre>
   1.204 +     *
   1.205 +     * @param  bytes the byte array to fill with random bytes
   1.206 +     * @throws NullPointerException if the byte array is null
   1.207 +     * @since  1.1
   1.208 +     */
   1.209 +    public void nextBytes(byte[] bytes) {
   1.210 +        for (int i = 0, len = bytes.length; i < len; )
   1.211 +            for (int rnd = nextInt(),
   1.212 +                     n = Math.min(len - i, Integer.SIZE/Byte.SIZE);
   1.213 +                 n-- > 0; rnd >>= Byte.SIZE)
   1.214 +                bytes[i++] = (byte)rnd;
   1.215 +    }
   1.216 +
   1.217 +    /**
   1.218 +     * Returns the next pseudorandom, uniformly distributed {@code int}
   1.219 +     * value from this random number generator's sequence. The general
   1.220 +     * contract of {@code nextInt} is that one {@code int} value is
   1.221 +     * pseudorandomly generated and returned. All 2<font size="-1"><sup>32
   1.222 +     * </sup></font> possible {@code int} values are produced with
   1.223 +     * (approximately) equal probability.
   1.224 +     *
   1.225 +     * <p>The method {@code nextInt} is implemented by class {@code Random}
   1.226 +     * as if by:
   1.227 +     *  <pre> {@code
   1.228 +     * public int nextInt() {
   1.229 +     *   return next(32);
   1.230 +     * }}</pre>
   1.231 +     *
   1.232 +     * @return the next pseudorandom, uniformly distributed {@code int}
   1.233 +     *         value from this random number generator's sequence
   1.234 +     */
   1.235 +    public int nextInt() {
   1.236 +        return next(32);
   1.237 +    }
   1.238 +
   1.239 +    /**
   1.240 +     * Returns a pseudorandom, uniformly distributed {@code int} value
   1.241 +     * between 0 (inclusive) and the specified value (exclusive), drawn from
   1.242 +     * this random number generator's sequence.  The general contract of
   1.243 +     * {@code nextInt} is that one {@code int} value in the specified range
   1.244 +     * is pseudorandomly generated and returned.  All {@code n} possible
   1.245 +     * {@code int} values are produced with (approximately) equal
   1.246 +     * probability.  The method {@code nextInt(int n)} is implemented by
   1.247 +     * class {@code Random} as if by:
   1.248 +     *  <pre> {@code
   1.249 +     * public int nextInt(int n) {
   1.250 +     *   if (n <= 0)
   1.251 +     *     throw new IllegalArgumentException("n must be positive");
   1.252 +     *
   1.253 +     *   if ((n & -n) == n)  // i.e., n is a power of 2
   1.254 +     *     return (int)((n * (long)next(31)) >> 31);
   1.255 +     *
   1.256 +     *   int bits, val;
   1.257 +     *   do {
   1.258 +     *       bits = next(31);
   1.259 +     *       val = bits % n;
   1.260 +     *   } while (bits - val + (n-1) < 0);
   1.261 +     *   return val;
   1.262 +     * }}</pre>
   1.263 +     *
   1.264 +     * <p>The hedge "approximately" is used in the foregoing description only
   1.265 +     * because the next method is only approximately an unbiased source of
   1.266 +     * independently chosen bits.  If it were a perfect source of randomly
   1.267 +     * chosen bits, then the algorithm shown would choose {@code int}
   1.268 +     * values from the stated range with perfect uniformity.
   1.269 +     * <p>
   1.270 +     * The algorithm is slightly tricky.  It rejects values that would result
   1.271 +     * in an uneven distribution (due to the fact that 2^31 is not divisible
   1.272 +     * by n). The probability of a value being rejected depends on n.  The
   1.273 +     * worst case is n=2^30+1, for which the probability of a reject is 1/2,
   1.274 +     * and the expected number of iterations before the loop terminates is 2.
   1.275 +     * <p>
   1.276 +     * The algorithm treats the case where n is a power of two specially: it
   1.277 +     * returns the correct number of high-order bits from the underlying
   1.278 +     * pseudo-random number generator.  In the absence of special treatment,
   1.279 +     * the correct number of <i>low-order</i> bits would be returned.  Linear
   1.280 +     * congruential pseudo-random number generators such as the one
   1.281 +     * implemented by this class are known to have short periods in the
   1.282 +     * sequence of values of their low-order bits.  Thus, this special case
   1.283 +     * greatly increases the length of the sequence of values returned by
   1.284 +     * successive calls to this method if n is a small power of two.
   1.285 +     *
   1.286 +     * @param n the bound on the random number to be returned.  Must be
   1.287 +     *        positive.
   1.288 +     * @return the next pseudorandom, uniformly distributed {@code int}
   1.289 +     *         value between {@code 0} (inclusive) and {@code n} (exclusive)
   1.290 +     *         from this random number generator's sequence
   1.291 +     * @throws IllegalArgumentException if n is not positive
   1.292 +     * @since 1.2
   1.293 +     */
   1.294 +
   1.295 +    public int nextInt(int n) {
   1.296 +        if (n <= 0)
   1.297 +            throw new IllegalArgumentException("n must be positive");
   1.298 +
   1.299 +        if ((n & -n) == n)  // i.e., n is a power of 2
   1.300 +            return (int)((n * (long)next(31)) >> 31);
   1.301 +
   1.302 +        int bits, val;
   1.303 +        do {
   1.304 +            bits = next(31);
   1.305 +            val = bits % n;
   1.306 +        } while (bits - val + (n-1) < 0);
   1.307 +        return val;
   1.308 +    }
   1.309 +
   1.310 +    /**
   1.311 +     * Returns the next pseudorandom, uniformly distributed {@code long}
   1.312 +     * value from this random number generator's sequence. The general
   1.313 +     * contract of {@code nextLong} is that one {@code long} value is
   1.314 +     * pseudorandomly generated and returned.
   1.315 +     *
   1.316 +     * <p>The method {@code nextLong} is implemented by class {@code Random}
   1.317 +     * as if by:
   1.318 +     *  <pre> {@code
   1.319 +     * public long nextLong() {
   1.320 +     *   return ((long)next(32) << 32) + next(32);
   1.321 +     * }}</pre>
   1.322 +     *
   1.323 +     * Because class {@code Random} uses a seed with only 48 bits,
   1.324 +     * this algorithm will not return all possible {@code long} values.
   1.325 +     *
   1.326 +     * @return the next pseudorandom, uniformly distributed {@code long}
   1.327 +     *         value from this random number generator's sequence
   1.328 +     */
   1.329 +    public long nextLong() {
   1.330 +        // it's okay that the bottom word remains signed.
   1.331 +        return ((long)(next(32)) << 32) + next(32);
   1.332 +    }
   1.333 +
   1.334 +    /**
   1.335 +     * Returns the next pseudorandom, uniformly distributed
   1.336 +     * {@code boolean} value from this random number generator's
   1.337 +     * sequence. The general contract of {@code nextBoolean} is that one
   1.338 +     * {@code boolean} value is pseudorandomly generated and returned.  The
   1.339 +     * values {@code true} and {@code false} are produced with
   1.340 +     * (approximately) equal probability.
   1.341 +     *
   1.342 +     * <p>The method {@code nextBoolean} is implemented by class {@code Random}
   1.343 +     * as if by:
   1.344 +     *  <pre> {@code
   1.345 +     * public boolean nextBoolean() {
   1.346 +     *   return next(1) != 0;
   1.347 +     * }}</pre>
   1.348 +     *
   1.349 +     * @return the next pseudorandom, uniformly distributed
   1.350 +     *         {@code boolean} value from this random number generator's
   1.351 +     *         sequence
   1.352 +     * @since 1.2
   1.353 +     */
   1.354 +    public boolean nextBoolean() {
   1.355 +        return next(1) != 0;
   1.356 +    }
   1.357 +
   1.358 +    /**
   1.359 +     * Returns the next pseudorandom, uniformly distributed {@code float}
   1.360 +     * value between {@code 0.0} and {@code 1.0} from this random
   1.361 +     * number generator's sequence.
   1.362 +     *
   1.363 +     * <p>The general contract of {@code nextFloat} is that one
   1.364 +     * {@code float} value, chosen (approximately) uniformly from the
   1.365 +     * range {@code 0.0f} (inclusive) to {@code 1.0f} (exclusive), is
   1.366 +     * pseudorandomly generated and returned. All 2<font
   1.367 +     * size="-1"><sup>24</sup></font> possible {@code float} values
   1.368 +     * of the form <i>m&nbsp;x&nbsp</i>2<font
   1.369 +     * size="-1"><sup>-24</sup></font>, where <i>m</i> is a positive
   1.370 +     * integer less than 2<font size="-1"><sup>24</sup> </font>, are
   1.371 +     * produced with (approximately) equal probability.
   1.372 +     *
   1.373 +     * <p>The method {@code nextFloat} is implemented by class {@code Random}
   1.374 +     * as if by:
   1.375 +     *  <pre> {@code
   1.376 +     * public float nextFloat() {
   1.377 +     *   return next(24) / ((float)(1 << 24));
   1.378 +     * }}</pre>
   1.379 +     *
   1.380 +     * <p>The hedge "approximately" is used in the foregoing description only
   1.381 +     * because the next method is only approximately an unbiased source of
   1.382 +     * independently chosen bits. If it were a perfect source of randomly
   1.383 +     * chosen bits, then the algorithm shown would choose {@code float}
   1.384 +     * values from the stated range with perfect uniformity.<p>
   1.385 +     * [In early versions of Java, the result was incorrectly calculated as:
   1.386 +     *  <pre> {@code
   1.387 +     *   return next(30) / ((float)(1 << 30));}</pre>
   1.388 +     * This might seem to be equivalent, if not better, but in fact it
   1.389 +     * introduced a slight nonuniformity because of the bias in the rounding
   1.390 +     * of floating-point numbers: it was slightly more likely that the
   1.391 +     * low-order bit of the significand would be 0 than that it would be 1.]
   1.392 +     *
   1.393 +     * @return the next pseudorandom, uniformly distributed {@code float}
   1.394 +     *         value between {@code 0.0} and {@code 1.0} from this
   1.395 +     *         random number generator's sequence
   1.396 +     */
   1.397 +    public float nextFloat() {
   1.398 +        return next(24) / ((float)(1 << 24));
   1.399 +    }
   1.400 +
   1.401 +    /**
   1.402 +     * Returns the next pseudorandom, uniformly distributed
   1.403 +     * {@code double} value between {@code 0.0} and
   1.404 +     * {@code 1.0} from this random number generator's sequence.
   1.405 +     *
   1.406 +     * <p>The general contract of {@code nextDouble} is that one
   1.407 +     * {@code double} value, chosen (approximately) uniformly from the
   1.408 +     * range {@code 0.0d} (inclusive) to {@code 1.0d} (exclusive), is
   1.409 +     * pseudorandomly generated and returned.
   1.410 +     *
   1.411 +     * <p>The method {@code nextDouble} is implemented by class {@code Random}
   1.412 +     * as if by:
   1.413 +     *  <pre> {@code
   1.414 +     * public double nextDouble() {
   1.415 +     *   return (((long)next(26) << 27) + next(27))
   1.416 +     *     / (double)(1L << 53);
   1.417 +     * }}</pre>
   1.418 +     *
   1.419 +     * <p>The hedge "approximately" is used in the foregoing description only
   1.420 +     * because the {@code next} method is only approximately an unbiased
   1.421 +     * source of independently chosen bits. If it were a perfect source of
   1.422 +     * randomly chosen bits, then the algorithm shown would choose
   1.423 +     * {@code double} values from the stated range with perfect uniformity.
   1.424 +     * <p>[In early versions of Java, the result was incorrectly calculated as:
   1.425 +     *  <pre> {@code
   1.426 +     *   return (((long)next(27) << 27) + next(27))
   1.427 +     *     / (double)(1L << 54);}</pre>
   1.428 +     * This might seem to be equivalent, if not better, but in fact it
   1.429 +     * introduced a large nonuniformity because of the bias in the rounding
   1.430 +     * of floating-point numbers: it was three times as likely that the
   1.431 +     * low-order bit of the significand would be 0 than that it would be 1!
   1.432 +     * This nonuniformity probably doesn't matter much in practice, but we
   1.433 +     * strive for perfection.]
   1.434 +     *
   1.435 +     * @return the next pseudorandom, uniformly distributed {@code double}
   1.436 +     *         value between {@code 0.0} and {@code 1.0} from this
   1.437 +     *         random number generator's sequence
   1.438 +     * @see Math#random
   1.439 +     */
   1.440 +    public double nextDouble() {
   1.441 +        return (((long)(next(26)) << 27) + next(27))
   1.442 +            / (double)(1L << 53);
   1.443 +    }
   1.444 +
   1.445 +    private double nextNextGaussian;
   1.446 +    private boolean haveNextNextGaussian = false;
   1.447 +
   1.448 +    /**
   1.449 +     * Returns the next pseudorandom, Gaussian ("normally") distributed
   1.450 +     * {@code double} value with mean {@code 0.0} and standard
   1.451 +     * deviation {@code 1.0} from this random number generator's sequence.
   1.452 +     * <p>
   1.453 +     * The general contract of {@code nextGaussian} is that one
   1.454 +     * {@code double} value, chosen from (approximately) the usual
   1.455 +     * normal distribution with mean {@code 0.0} and standard deviation
   1.456 +     * {@code 1.0}, is pseudorandomly generated and returned.
   1.457 +     *
   1.458 +     * <p>The method {@code nextGaussian} is implemented by class
   1.459 +     * {@code Random} as if by a threadsafe version of the following:
   1.460 +     *  <pre> {@code
   1.461 +     * private double nextNextGaussian;
   1.462 +     * private boolean haveNextNextGaussian = false;
   1.463 +     *
   1.464 +     * public double nextGaussian() {
   1.465 +     *   if (haveNextNextGaussian) {
   1.466 +     *     haveNextNextGaussian = false;
   1.467 +     *     return nextNextGaussian;
   1.468 +     *   } else {
   1.469 +     *     double v1, v2, s;
   1.470 +     *     do {
   1.471 +     *       v1 = 2 * nextDouble() - 1;   // between -1.0 and 1.0
   1.472 +     *       v2 = 2 * nextDouble() - 1;   // between -1.0 and 1.0
   1.473 +     *       s = v1 * v1 + v2 * v2;
   1.474 +     *     } while (s >= 1 || s == 0);
   1.475 +     *     double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s);
   1.476 +     *     nextNextGaussian = v2 * multiplier;
   1.477 +     *     haveNextNextGaussian = true;
   1.478 +     *     return v1 * multiplier;
   1.479 +     *   }
   1.480 +     * }}</pre>
   1.481 +     * This uses the <i>polar method</i> of G. E. P. Box, M. E. Muller, and
   1.482 +     * G. Marsaglia, as described by Donald E. Knuth in <i>The Art of
   1.483 +     * Computer Programming</i>, Volume 3: <i>Seminumerical Algorithms</i>,
   1.484 +     * section 3.4.1, subsection C, algorithm P. Note that it generates two
   1.485 +     * independent values at the cost of only one call to {@code StrictMath.log}
   1.486 +     * and one call to {@code StrictMath.sqrt}.
   1.487 +     *
   1.488 +     * @return the next pseudorandom, Gaussian ("normally") distributed
   1.489 +     *         {@code double} value with mean {@code 0.0} and
   1.490 +     *         standard deviation {@code 1.0} from this random number
   1.491 +     *         generator's sequence
   1.492 +     */
   1.493 +    synchronized public double nextGaussian() {
   1.494 +        // See Knuth, ACP, Section 3.4.1 Algorithm C.
   1.495 +        if (haveNextNextGaussian) {
   1.496 +            haveNextNextGaussian = false;
   1.497 +            return nextNextGaussian;
   1.498 +        } else {
   1.499 +            double v1, v2, s;
   1.500 +            do {
   1.501 +                v1 = 2 * nextDouble() - 1; // between -1 and 1
   1.502 +                v2 = 2 * nextDouble() - 1; // between -1 and 1
   1.503 +                s = v1 * v1 + v2 * v2;
   1.504 +            } while (s >= 1 || s == 0);
   1.505 +            double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s);
   1.506 +            nextNextGaussian = v2 * multiplier;
   1.507 +            haveNextNextGaussian = true;
   1.508 +            return v1 * multiplier;
   1.509 +        }
   1.510 +    }
   1.511 +
   1.512 +    /**
   1.513 +     * Serializable fields for Random.
   1.514 +     *
   1.515 +     * @serialField    seed long
   1.516 +     *              seed for random computations
   1.517 +     * @serialField    nextNextGaussian double
   1.518 +     *              next Gaussian to be returned
   1.519 +     * @serialField      haveNextNextGaussian boolean
   1.520 +     *              nextNextGaussian is valid
   1.521 +     */
   1.522 +    private static final ObjectStreamField[] serialPersistentFields = {
   1.523 +        new ObjectStreamField("seed", Long.TYPE),
   1.524 +        new ObjectStreamField("nextNextGaussian", Double.TYPE),
   1.525 +        new ObjectStreamField("haveNextNextGaussian", Boolean.TYPE)
   1.526 +    };
   1.527 +
   1.528 +    /**
   1.529 +     * Reconstitute the {@code Random} instance from a stream (that is,
   1.530 +     * deserialize it).
   1.531 +     */
   1.532 +    private void readObject(java.io.ObjectInputStream s)
   1.533 +        throws java.io.IOException, ClassNotFoundException {
   1.534 +
   1.535 +        ObjectInputStream.GetField fields = s.readFields();
   1.536 +
   1.537 +        // The seed is read in as {@code long} for
   1.538 +        // historical reasons, but it is converted to an AtomicLong.
   1.539 +        long seedVal = fields.get("seed", -1L);
   1.540 +        if (seedVal < 0)
   1.541 +          throw new java.io.StreamCorruptedException(
   1.542 +                              "Random: invalid seed");
   1.543 +        resetSeed(seedVal);
   1.544 +        nextNextGaussian = fields.get("nextNextGaussian", 0.0);
   1.545 +        haveNextNextGaussian = fields.get("haveNextNextGaussian", false);
   1.546 +    }
   1.547 +
   1.548 +    /**
   1.549 +     * Save the {@code Random} instance to a stream.
   1.550 +     */
   1.551 +    synchronized private void writeObject(ObjectOutputStream s)
   1.552 +        throws IOException {
   1.553 +
   1.554 +        // set the values of the Serializable fields
   1.555 +        ObjectOutputStream.PutField fields = s.putFields();
   1.556 +
   1.557 +        // The seed is serialized as a long for historical reasons.
   1.558 +        fields.put("seed", seed.get());
   1.559 +        fields.put("nextNextGaussian", nextNextGaussian);
   1.560 +        fields.put("haveNextNextGaussian", haveNextNextGaussian);
   1.561 +
   1.562 +        // save them
   1.563 +        s.writeFields();
   1.564 +    }
   1.565 +
   1.566 +    // Support for resetting seed while deserializing
   1.567 +    private static final Unsafe unsafe = Unsafe.getUnsafe();
   1.568 +    private static final long seedOffset;
   1.569 +    static {
   1.570 +        try {
   1.571 +            seedOffset = unsafe.objectFieldOffset
   1.572 +                (Random.class.getDeclaredField("seed"));
   1.573 +        } catch (Exception ex) { throw new Error(ex); }
   1.574 +    }
   1.575 +    private void resetSeed(long seedVal) {
   1.576 +        unsafe.putObjectVolatile(this, seedOffset, new AtomicLong(seedVal));
   1.577 +    }
   1.578 +}