Moving modules around so the runtime is under one master pom and can be built without building other modules that are in the repository
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.
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.
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).
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.
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
28 import org.apidesign.bck2brwsr.emul.lang.System;
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.)
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.
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.
50 * Many applications will find the method {@link Math#random} simpler to use.
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
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.
64 * @author Frank Yellin
68 class Random implements java.io.Serializable {
69 /** use serialVersionUID from JDK 1.1 for interoperability */
70 static final long serialVersionUID = 3905348978240129619L;
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.)
79 private static final long multiplier = 0x5DEECE66DL;
80 private static final long addend = 0xBL;
81 private static final long mask = (1L << 48) - 1;
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.
89 this(seedUniquifier() ^ System.nanoTime());
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;
101 private static long seedUniquifier = 8682522807148012L;
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}.
108 * <p>The invocation {@code new Random(seed)} is equivalent to:
110 * Random rnd = new Random();
111 * rnd.setSeed(seed);}</pre>
113 * @param seed the initial seed
114 * @see #setSeed(long)
116 public Random(long seed) {
117 this.seed = initialScramble(seed);
120 private static long initialScramble(long seed) {
121 return (seed ^ multiplier) & mask;
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
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.
141 * @param seed the initial seed
143 synchronized public void setSeed(long seed) {
144 this.seed = initialScramble(seed);
145 haveNextNextGaussian = false;
149 * Generates the next pseudorandom number. Subclasses should
150 * override this, as this is used by all other methods.
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>
161 * <pre>{@code (int)(seed >>> (48 - bits))}.</pre>
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.
168 * @param bits random bits
169 * @return the next pseudorandom value from this random number
170 * generator's sequence
173 protected synchronized int next(int bits) {
174 long oldseed, nextseed;
175 long seed = this.seed;
177 nextseed = (oldseed * multiplier + addend) & mask;
178 this.seed = nextseed;
179 return (int)(nextseed >>> (48 - bits));
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.
187 * <p>The method {@code nextBytes} is implemented by class {@code Random}
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;
197 * @param bytes the byte array to fill with random bytes
198 * @throws NullPointerException if the byte array is null
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;
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.
217 * <p>The method {@code nextInt} is implemented by class {@code Random}
220 * public int nextInt() {
224 * @return the next pseudorandom, uniformly distributed {@code int}
225 * value from this random number generator's sequence
227 public int nextInt() {
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:
241 * public int nextInt(int n) {
243 * throw new IllegalArgumentException("n must be positive");
245 * if ((n & -n) == n) // i.e., n is a power of 2
246 * return (int)((n * (long)next(31)) >> 31);
252 * } while (bits - val + (n-1) < 0);
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.
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.
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.
278 * @param n the bound on the random number to be returned. Must be
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
287 public int nextInt(int n) {
289 throw new IllegalArgumentException("n must be positive");
291 if ((n & -n) == n) // i.e., n is a power of 2
292 return (int)((n * (long)next(31)) >> 31);
298 } while (bits - val + (n-1) < 0);
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.
308 * <p>The method {@code nextLong} is implemented by class {@code Random}
311 * public long nextLong() {
312 * return ((long)next(32) << 32) + next(32);
315 * Because class {@code Random} uses a seed with only 48 bits,
316 * this algorithm will not return all possible {@code long} values.
318 * @return the next pseudorandom, uniformly distributed {@code long}
319 * value from this random number generator's sequence
321 public long nextLong() {
322 // it's okay that the bottom word remains signed.
323 return ((long)(next(32)) << 32) + next(32);
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.
334 * <p>The method {@code nextBoolean} is implemented by class {@code Random}
337 * public boolean nextBoolean() {
338 * return next(1) != 0;
341 * @return the next pseudorandom, uniformly distributed
342 * {@code boolean} value from this random number generator's
346 public boolean nextBoolean() {
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.
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 x </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.
365 * <p>The method {@code nextFloat} is implemented by class {@code Random}
368 * public float nextFloat() {
369 * return next(24) / ((float)(1 << 24));
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:
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.]
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
389 public float nextFloat() {
390 return next(24) / ((float)(1 << 24));
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.
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.
403 * <p>The method {@code nextDouble} is implemented by class {@code Random}
406 * public double nextDouble() {
407 * return (((long)next(26) << 27) + next(27))
408 * / (double)(1L << 53);
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:
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.]
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
432 public double nextDouble() {
433 return (((long)(next(26)) << 27) + next(27))
434 / (double)(1L << 53);
437 private double nextNextGaussian;
438 private boolean haveNextNextGaussian = false;
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.
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.
450 * <p>The method {@code nextGaussian} is implemented by class
451 * {@code Random} as if by a threadsafe version of the following:
453 * private double nextNextGaussian;
454 * private boolean haveNextNextGaussian = false;
456 * public double nextGaussian() {
457 * if (haveNextNextGaussian) {
458 * haveNextNextGaussian = false;
459 * return nextNextGaussian;
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;
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}.
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
485 synchronized public double nextGaussian() {
486 // See Knuth, ACP, Section 3.4.1 Algorithm C.
487 if (haveNextNextGaussian) {
488 haveNextNextGaussian = false;
489 return nextNextGaussian;
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;