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