1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/rt/emul/compact/src/main/java/java/util/Random.java Tue Feb 26 16:54:16 2013 +0100
1.3 @@ -0,0 +1,503 @@
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 +
1.31 +import org.apidesign.bck2brwsr.emul.lang.System;
1.32 +
1.33 +/**
1.34 + * An instance of this class is used to generate a stream of
1.35 + * pseudorandom numbers. The class uses a 48-bit seed, which is
1.36 + * modified using a linear congruential formula. (See Donald Knuth,
1.37 + * <i>The Art of Computer Programming, Volume 2</i>, Section 3.2.1.)
1.38 + * <p>
1.39 + * If two instances of {@code Random} are created with the same
1.40 + * seed, and the same sequence of method calls is made for each, they
1.41 + * will generate and return identical sequences of numbers. In order to
1.42 + * guarantee this property, particular algorithms are specified for the
1.43 + * class {@code Random}. Java implementations must use all the algorithms
1.44 + * shown here for the class {@code Random}, for the sake of absolute
1.45 + * portability of Java code. However, subclasses of class {@code Random}
1.46 + * are permitted to use other algorithms, so long as they adhere to the
1.47 + * general contracts for all the methods.
1.48 + * <p>
1.49 + * The algorithms implemented by class {@code Random} use a
1.50 + * {@code protected} utility method that on each invocation can supply
1.51 + * up to 32 pseudorandomly generated bits.
1.52 + * <p>
1.53 + * Many applications will find the method {@link Math#random} simpler to use.
1.54 + *
1.55 + * <p>Instances of {@code java.util.Random} are threadsafe.
1.56 + * However, the concurrent use of the same {@code java.util.Random}
1.57 + * instance across threads may encounter contention and consequent
1.58 + * poor performance. Consider instead using
1.59 + * {@link java.util.concurrent.ThreadLocalRandom} in multithreaded
1.60 + * designs.
1.61 + *
1.62 + * <p>Instances of {@code java.util.Random} are not cryptographically
1.63 + * secure. Consider instead using {@link java.security.SecureRandom} to
1.64 + * get a cryptographically secure pseudo-random number generator for use
1.65 + * by security-sensitive applications.
1.66 + *
1.67 + * @author Frank Yellin
1.68 + * @since 1.0
1.69 + */
1.70 +public
1.71 +class Random implements java.io.Serializable {
1.72 + /** use serialVersionUID from JDK 1.1 for interoperability */
1.73 + static final long serialVersionUID = 3905348978240129619L;
1.74 +
1.75 + /**
1.76 + * The internal state associated with this pseudorandom number generator.
1.77 + * (The specs for the methods in this class describe the ongoing
1.78 + * computation of this value.)
1.79 + */
1.80 + private long seed;
1.81 +
1.82 + private static final long multiplier = 0x5DEECE66DL;
1.83 + private static final long addend = 0xBL;
1.84 + private static final long mask = (1L << 48) - 1;
1.85 +
1.86 + /**
1.87 + * Creates a new random number generator. This constructor sets
1.88 + * the seed of the random number generator to a value very likely
1.89 + * to be distinct from any other invocation of this constructor.
1.90 + */
1.91 + public Random() {
1.92 + this(seedUniquifier() ^ System.nanoTime());
1.93 + }
1.94 +
1.95 + private static synchronized long seedUniquifier() {
1.96 + // L'Ecuyer, "Tables of Linear Congruential Generators of
1.97 + // Different Sizes and Good Lattice Structure", 1999
1.98 + long current = seedUniquifier;
1.99 + long next = current * 181783497276652981L;
1.100 + seedUniquifier = next;
1.101 + return next;
1.102 + }
1.103 +
1.104 + private static long seedUniquifier = 8682522807148012L;
1.105 +
1.106 + /**
1.107 + * Creates a new random number generator using a single {@code long} seed.
1.108 + * The seed is the initial value of the internal state of the pseudorandom
1.109 + * number generator which is maintained by method {@link #next}.
1.110 + *
1.111 + * <p>The invocation {@code new Random(seed)} is equivalent to:
1.112 + * <pre> {@code
1.113 + * Random rnd = new Random();
1.114 + * rnd.setSeed(seed);}</pre>
1.115 + *
1.116 + * @param seed the initial seed
1.117 + * @see #setSeed(long)
1.118 + */
1.119 + public Random(long seed) {
1.120 + this.seed = initialScramble(seed);
1.121 + }
1.122 +
1.123 + private static long initialScramble(long seed) {
1.124 + return (seed ^ multiplier) & mask;
1.125 + }
1.126 +
1.127 + /**
1.128 + * Sets the seed of this random number generator using a single
1.129 + * {@code long} seed. The general contract of {@code setSeed} is
1.130 + * that it alters the state of this random number generator object
1.131 + * so as to be in exactly the same state as if it had just been
1.132 + * created with the argument {@code seed} as a seed. The method
1.133 + * {@code setSeed} is implemented by class {@code Random} by
1.134 + * atomically updating the seed to
1.135 + * <pre>{@code (seed ^ 0x5DEECE66DL) & ((1L << 48) - 1)}</pre>
1.136 + * and clearing the {@code haveNextNextGaussian} flag used by {@link
1.137 + * #nextGaussian}.
1.138 + *
1.139 + * <p>The implementation of {@code setSeed} by class {@code Random}
1.140 + * happens to use only 48 bits of the given seed. In general, however,
1.141 + * an overriding method may use all 64 bits of the {@code long}
1.142 + * argument as a seed value.
1.143 + *
1.144 + * @param seed the initial seed
1.145 + */
1.146 + synchronized public void setSeed(long seed) {
1.147 + this.seed = initialScramble(seed);
1.148 + haveNextNextGaussian = false;
1.149 + }
1.150 +
1.151 + /**
1.152 + * Generates the next pseudorandom number. Subclasses should
1.153 + * override this, as this is used by all other methods.
1.154 + *
1.155 + * <p>The general contract of {@code next} is that it returns an
1.156 + * {@code int} value and if the argument {@code bits} is between
1.157 + * {@code 1} and {@code 32} (inclusive), then that many low-order
1.158 + * bits of the returned value will be (approximately) independently
1.159 + * chosen bit values, each of which is (approximately) equally
1.160 + * likely to be {@code 0} or {@code 1}. The method {@code next} is
1.161 + * implemented by class {@code Random} by atomically updating the seed to
1.162 + * <pre>{@code (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1)}</pre>
1.163 + * and returning
1.164 + * <pre>{@code (int)(seed >>> (48 - bits))}.</pre>
1.165 + *
1.166 + * This is a linear congruential pseudorandom number generator, as
1.167 + * defined by D. H. Lehmer and described by Donald E. Knuth in
1.168 + * <i>The Art of Computer Programming,</i> Volume 3:
1.169 + * <i>Seminumerical Algorithms</i>, section 3.2.1.
1.170 + *
1.171 + * @param bits random bits
1.172 + * @return the next pseudorandom value from this random number
1.173 + * generator's sequence
1.174 + * @since 1.1
1.175 + */
1.176 + protected synchronized int next(int bits) {
1.177 + long oldseed, nextseed;
1.178 + long seed = this.seed;
1.179 + oldseed = seed;
1.180 + nextseed = (oldseed * multiplier + addend) & mask;
1.181 + this.seed = nextseed;
1.182 + return (int)(nextseed >>> (48 - bits));
1.183 + }
1.184 +
1.185 + /**
1.186 + * Generates random bytes and places them into a user-supplied
1.187 + * byte array. The number of random bytes produced is equal to
1.188 + * the length of the byte array.
1.189 + *
1.190 + * <p>The method {@code nextBytes} is implemented by class {@code Random}
1.191 + * as if by:
1.192 + * <pre> {@code
1.193 + * public void nextBytes(byte[] bytes) {
1.194 + * for (int i = 0; i < bytes.length; )
1.195 + * for (int rnd = nextInt(), n = Math.min(bytes.length - i, 4);
1.196 + * n-- > 0; rnd >>= 8)
1.197 + * bytes[i++] = (byte)rnd;
1.198 + * }}</pre>
1.199 + *
1.200 + * @param bytes the byte array to fill with random bytes
1.201 + * @throws NullPointerException if the byte array is null
1.202 + * @since 1.1
1.203 + */
1.204 + public void nextBytes(byte[] bytes) {
1.205 + for (int i = 0, len = bytes.length; i < len; )
1.206 + for (int rnd = nextInt(),
1.207 + n = Math.min(len - i, Integer.SIZE/Byte.SIZE);
1.208 + n-- > 0; rnd >>= Byte.SIZE)
1.209 + bytes[i++] = (byte)rnd;
1.210 + }
1.211 +
1.212 + /**
1.213 + * Returns the next pseudorandom, uniformly distributed {@code int}
1.214 + * value from this random number generator's sequence. The general
1.215 + * contract of {@code nextInt} is that one {@code int} value is
1.216 + * pseudorandomly generated and returned. All 2<font size="-1"><sup>32
1.217 + * </sup></font> possible {@code int} values are produced with
1.218 + * (approximately) equal probability.
1.219 + *
1.220 + * <p>The method {@code nextInt} is implemented by class {@code Random}
1.221 + * as if by:
1.222 + * <pre> {@code
1.223 + * public int nextInt() {
1.224 + * return next(32);
1.225 + * }}</pre>
1.226 + *
1.227 + * @return the next pseudorandom, uniformly distributed {@code int}
1.228 + * value from this random number generator's sequence
1.229 + */
1.230 + public int nextInt() {
1.231 + return next(32);
1.232 + }
1.233 +
1.234 + /**
1.235 + * Returns a pseudorandom, uniformly distributed {@code int} value
1.236 + * between 0 (inclusive) and the specified value (exclusive), drawn from
1.237 + * this random number generator's sequence. The general contract of
1.238 + * {@code nextInt} is that one {@code int} value in the specified range
1.239 + * is pseudorandomly generated and returned. All {@code n} possible
1.240 + * {@code int} values are produced with (approximately) equal
1.241 + * probability. The method {@code nextInt(int n)} is implemented by
1.242 + * class {@code Random} as if by:
1.243 + * <pre> {@code
1.244 + * public int nextInt(int n) {
1.245 + * if (n <= 0)
1.246 + * throw new IllegalArgumentException("n must be positive");
1.247 + *
1.248 + * if ((n & -n) == n) // i.e., n is a power of 2
1.249 + * return (int)((n * (long)next(31)) >> 31);
1.250 + *
1.251 + * int bits, val;
1.252 + * do {
1.253 + * bits = next(31);
1.254 + * val = bits % n;
1.255 + * } while (bits - val + (n-1) < 0);
1.256 + * return val;
1.257 + * }}</pre>
1.258 + *
1.259 + * <p>The hedge "approximately" is used in the foregoing description only
1.260 + * because the next method is only approximately an unbiased source of
1.261 + * independently chosen bits. If it were a perfect source of randomly
1.262 + * chosen bits, then the algorithm shown would choose {@code int}
1.263 + * values from the stated range with perfect uniformity.
1.264 + * <p>
1.265 + * The algorithm is slightly tricky. It rejects values that would result
1.266 + * in an uneven distribution (due to the fact that 2^31 is not divisible
1.267 + * by n). The probability of a value being rejected depends on n. The
1.268 + * worst case is n=2^30+1, for which the probability of a reject is 1/2,
1.269 + * and the expected number of iterations before the loop terminates is 2.
1.270 + * <p>
1.271 + * The algorithm treats the case where n is a power of two specially: it
1.272 + * returns the correct number of high-order bits from the underlying
1.273 + * pseudo-random number generator. In the absence of special treatment,
1.274 + * the correct number of <i>low-order</i> bits would be returned. Linear
1.275 + * congruential pseudo-random number generators such as the one
1.276 + * implemented by this class are known to have short periods in the
1.277 + * sequence of values of their low-order bits. Thus, this special case
1.278 + * greatly increases the length of the sequence of values returned by
1.279 + * successive calls to this method if n is a small power of two.
1.280 + *
1.281 + * @param n the bound on the random number to be returned. Must be
1.282 + * positive.
1.283 + * @return the next pseudorandom, uniformly distributed {@code int}
1.284 + * value between {@code 0} (inclusive) and {@code n} (exclusive)
1.285 + * from this random number generator's sequence
1.286 + * @throws IllegalArgumentException if n is not positive
1.287 + * @since 1.2
1.288 + */
1.289 +
1.290 + public int nextInt(int n) {
1.291 + if (n <= 0)
1.292 + throw new IllegalArgumentException("n must be positive");
1.293 +
1.294 + if ((n & -n) == n) // i.e., n is a power of 2
1.295 + return (int)((n * (long)next(31)) >> 31);
1.296 +
1.297 + int bits, val;
1.298 + do {
1.299 + bits = next(31);
1.300 + val = bits % n;
1.301 + } while (bits - val + (n-1) < 0);
1.302 + return val;
1.303 + }
1.304 +
1.305 + /**
1.306 + * Returns the next pseudorandom, uniformly distributed {@code long}
1.307 + * value from this random number generator's sequence. The general
1.308 + * contract of {@code nextLong} is that one {@code long} value is
1.309 + * pseudorandomly generated and returned.
1.310 + *
1.311 + * <p>The method {@code nextLong} is implemented by class {@code Random}
1.312 + * as if by:
1.313 + * <pre> {@code
1.314 + * public long nextLong() {
1.315 + * return ((long)next(32) << 32) + next(32);
1.316 + * }}</pre>
1.317 + *
1.318 + * Because class {@code Random} uses a seed with only 48 bits,
1.319 + * this algorithm will not return all possible {@code long} values.
1.320 + *
1.321 + * @return the next pseudorandom, uniformly distributed {@code long}
1.322 + * value from this random number generator's sequence
1.323 + */
1.324 + public long nextLong() {
1.325 + // it's okay that the bottom word remains signed.
1.326 + return ((long)(next(32)) << 32) + next(32);
1.327 + }
1.328 +
1.329 + /**
1.330 + * Returns the next pseudorandom, uniformly distributed
1.331 + * {@code boolean} value from this random number generator's
1.332 + * sequence. The general contract of {@code nextBoolean} is that one
1.333 + * {@code boolean} value is pseudorandomly generated and returned. The
1.334 + * values {@code true} and {@code false} are produced with
1.335 + * (approximately) equal probability.
1.336 + *
1.337 + * <p>The method {@code nextBoolean} is implemented by class {@code Random}
1.338 + * as if by:
1.339 + * <pre> {@code
1.340 + * public boolean nextBoolean() {
1.341 + * return next(1) != 0;
1.342 + * }}</pre>
1.343 + *
1.344 + * @return the next pseudorandom, uniformly distributed
1.345 + * {@code boolean} value from this random number generator's
1.346 + * sequence
1.347 + * @since 1.2
1.348 + */
1.349 + public boolean nextBoolean() {
1.350 + return next(1) != 0;
1.351 + }
1.352 +
1.353 + /**
1.354 + * Returns the next pseudorandom, uniformly distributed {@code float}
1.355 + * value between {@code 0.0} and {@code 1.0} from this random
1.356 + * number generator's sequence.
1.357 + *
1.358 + * <p>The general contract of {@code nextFloat} is that one
1.359 + * {@code float} value, chosen (approximately) uniformly from the
1.360 + * range {@code 0.0f} (inclusive) to {@code 1.0f} (exclusive), is
1.361 + * pseudorandomly generated and returned. All 2<font
1.362 + * size="-1"><sup>24</sup></font> possible {@code float} values
1.363 + * of the form <i>m x </i>2<font
1.364 + * size="-1"><sup>-24</sup></font>, where <i>m</i> is a positive
1.365 + * integer less than 2<font size="-1"><sup>24</sup> </font>, are
1.366 + * produced with (approximately) equal probability.
1.367 + *
1.368 + * <p>The method {@code nextFloat} is implemented by class {@code Random}
1.369 + * as if by:
1.370 + * <pre> {@code
1.371 + * public float nextFloat() {
1.372 + * return next(24) / ((float)(1 << 24));
1.373 + * }}</pre>
1.374 + *
1.375 + * <p>The hedge "approximately" is used in the foregoing description only
1.376 + * because the next method is only approximately an unbiased source of
1.377 + * independently chosen bits. If it were a perfect source of randomly
1.378 + * chosen bits, then the algorithm shown would choose {@code float}
1.379 + * values from the stated range with perfect uniformity.<p>
1.380 + * [In early versions of Java, the result was incorrectly calculated as:
1.381 + * <pre> {@code
1.382 + * return next(30) / ((float)(1 << 30));}</pre>
1.383 + * This might seem to be equivalent, if not better, but in fact it
1.384 + * introduced a slight nonuniformity because of the bias in the rounding
1.385 + * of floating-point numbers: it was slightly more likely that the
1.386 + * low-order bit of the significand would be 0 than that it would be 1.]
1.387 + *
1.388 + * @return the next pseudorandom, uniformly distributed {@code float}
1.389 + * value between {@code 0.0} and {@code 1.0} from this
1.390 + * random number generator's sequence
1.391 + */
1.392 + public float nextFloat() {
1.393 + return next(24) / ((float)(1 << 24));
1.394 + }
1.395 +
1.396 + /**
1.397 + * Returns the next pseudorandom, uniformly distributed
1.398 + * {@code double} value between {@code 0.0} and
1.399 + * {@code 1.0} from this random number generator's sequence.
1.400 + *
1.401 + * <p>The general contract of {@code nextDouble} is that one
1.402 + * {@code double} value, chosen (approximately) uniformly from the
1.403 + * range {@code 0.0d} (inclusive) to {@code 1.0d} (exclusive), is
1.404 + * pseudorandomly generated and returned.
1.405 + *
1.406 + * <p>The method {@code nextDouble} is implemented by class {@code Random}
1.407 + * as if by:
1.408 + * <pre> {@code
1.409 + * public double nextDouble() {
1.410 + * return (((long)next(26) << 27) + next(27))
1.411 + * / (double)(1L << 53);
1.412 + * }}</pre>
1.413 + *
1.414 + * <p>The hedge "approximately" is used in the foregoing description only
1.415 + * because the {@code next} method is only approximately an unbiased
1.416 + * source of independently chosen bits. If it were a perfect source of
1.417 + * randomly chosen bits, then the algorithm shown would choose
1.418 + * {@code double} values from the stated range with perfect uniformity.
1.419 + * <p>[In early versions of Java, the result was incorrectly calculated as:
1.420 + * <pre> {@code
1.421 + * return (((long)next(27) << 27) + next(27))
1.422 + * / (double)(1L << 54);}</pre>
1.423 + * This might seem to be equivalent, if not better, but in fact it
1.424 + * introduced a large nonuniformity because of the bias in the rounding
1.425 + * of floating-point numbers: it was three times as likely that the
1.426 + * low-order bit of the significand would be 0 than that it would be 1!
1.427 + * This nonuniformity probably doesn't matter much in practice, but we
1.428 + * strive for perfection.]
1.429 + *
1.430 + * @return the next pseudorandom, uniformly distributed {@code double}
1.431 + * value between {@code 0.0} and {@code 1.0} from this
1.432 + * random number generator's sequence
1.433 + * @see Math#random
1.434 + */
1.435 + public double nextDouble() {
1.436 + return (((long)(next(26)) << 27) + next(27))
1.437 + / (double)(1L << 53);
1.438 + }
1.439 +
1.440 + private double nextNextGaussian;
1.441 + private boolean haveNextNextGaussian = false;
1.442 +
1.443 + /**
1.444 + * Returns the next pseudorandom, Gaussian ("normally") distributed
1.445 + * {@code double} value with mean {@code 0.0} and standard
1.446 + * deviation {@code 1.0} from this random number generator's sequence.
1.447 + * <p>
1.448 + * The general contract of {@code nextGaussian} is that one
1.449 + * {@code double} value, chosen from (approximately) the usual
1.450 + * normal distribution with mean {@code 0.0} and standard deviation
1.451 + * {@code 1.0}, is pseudorandomly generated and returned.
1.452 + *
1.453 + * <p>The method {@code nextGaussian} is implemented by class
1.454 + * {@code Random} as if by a threadsafe version of the following:
1.455 + * <pre> {@code
1.456 + * private double nextNextGaussian;
1.457 + * private boolean haveNextNextGaussian = false;
1.458 + *
1.459 + * public double nextGaussian() {
1.460 + * if (haveNextNextGaussian) {
1.461 + * haveNextNextGaussian = false;
1.462 + * return nextNextGaussian;
1.463 + * } else {
1.464 + * double v1, v2, s;
1.465 + * do {
1.466 + * v1 = 2 * nextDouble() - 1; // between -1.0 and 1.0
1.467 + * v2 = 2 * nextDouble() - 1; // between -1.0 and 1.0
1.468 + * s = v1 * v1 + v2 * v2;
1.469 + * } while (s >= 1 || s == 0);
1.470 + * double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s);
1.471 + * nextNextGaussian = v2 * multiplier;
1.472 + * haveNextNextGaussian = true;
1.473 + * return v1 * multiplier;
1.474 + * }
1.475 + * }}</pre>
1.476 + * This uses the <i>polar method</i> of G. E. P. Box, M. E. Muller, and
1.477 + * G. Marsaglia, as described by Donald E. Knuth in <i>The Art of
1.478 + * Computer Programming</i>, Volume 3: <i>Seminumerical Algorithms</i>,
1.479 + * section 3.4.1, subsection C, algorithm P. Note that it generates two
1.480 + * independent values at the cost of only one call to {@code StrictMath.log}
1.481 + * and one call to {@code StrictMath.sqrt}.
1.482 + *
1.483 + * @return the next pseudorandom, Gaussian ("normally") distributed
1.484 + * {@code double} value with mean {@code 0.0} and
1.485 + * standard deviation {@code 1.0} from this random number
1.486 + * generator's sequence
1.487 + */
1.488 + synchronized public double nextGaussian() {
1.489 + // See Knuth, ACP, Section 3.4.1 Algorithm C.
1.490 + if (haveNextNextGaussian) {
1.491 + haveNextNextGaussian = false;
1.492 + return nextNextGaussian;
1.493 + } else {
1.494 + double v1, v2, s;
1.495 + do {
1.496 + v1 = 2 * nextDouble() - 1; // between -1 and 1
1.497 + v2 = 2 * nextDouble() - 1; // between -1 and 1
1.498 + s = v1 * v1 + v2 * v2;
1.499 + } while (s >= 1 || s == 0);
1.500 + double multiplier = Math.sqrt(-2 * Math.log(s)/s);
1.501 + nextNextGaussian = v2 * multiplier;
1.502 + haveNextNextGaussian = true;
1.503 + return v1 * multiplier;
1.504 + }
1.505 + }
1.506 +}