001 /*
002 * Copyright 1995-2007 Sun Microsystems, Inc. All Rights Reserved.
003 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
004 *
005 * This code is free software; you can redistribute it and/or modify it
006 * under the terms of the GNU General Public License version 2 only, as
007 * published by the Free Software Foundation. Sun designates this
008 * particular file as subject to the "Classpath" exception as provided
009 * by Sun in the LICENSE file that accompanied this code.
010 *
011 * This code is distributed in the hope that it will be useful, but WITHOUT
012 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
013 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
014 * version 2 for more details (a copy is included in the LICENSE file that
015 * accompanied this code).
016 *
017 * You should have received a copy of the GNU General Public License version
018 * 2 along with this work; if not, write to the Free Software Foundation,
019 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
020 *
021 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
022 * CA 95054 USA or visit www.sun.com if you need additional information or
023 * have any questions.
024 */
025
026 package java.util;
027
028 import java.io.*;
029 import java.util.concurrent.atomic.AtomicLong;
030 import sun.misc.Unsafe;
031
032 /**
033 * An instance of this class is used to generate a stream of
034 * pseudorandom numbers. The class uses a 48-bit seed, which is
035 * modified using a linear congruential formula. (See Donald Knuth,
036 * <i>The Art of Computer Programming, Volume 3</i>, Section 3.2.1.)
037 * <p>
038 * If two instances of {@code Random} are created with the same
039 * seed, and the same sequence of method calls is made for each, they
040 * will generate and return identical sequences of numbers. In order to
041 * guarantee this property, particular algorithms are specified for the
042 * class {@code Random}. Java implementations must use all the algorithms
043 * shown here for the class {@code Random}, for the sake of absolute
044 * portability of Java code. However, subclasses of class {@code Random}
045 * are permitted to use other algorithms, so long as they adhere to the
046 * general contracts for all the methods.
047 * <p>
048 * The algorithms implemented by class {@code Random} use a
049 * {@code protected} utility method that on each invocation can supply
050 * up to 32 pseudorandomly generated bits.
051 * <p>
052 * Many applications will find the method {@link Math#random} simpler to use.
053 *
054 * @author Frank Yellin
055 * @version 1.54, 05/05/07
056 * @since 1.0
057 */
058 public class Random implements java.io.Serializable {
059 /** use serialVersionUID from JDK 1.1 for interoperability */
060 static final long serialVersionUID = 3905348978240129619L;
061
062 /**
063 * The internal state associated with this pseudorandom number generator.
064 * (The specs for the methods in this class describe the ongoing
065 * computation of this value.)
066 */
067 private final AtomicLong seed;
068
069 private final static long multiplier = 0x5DEECE66DL;
070 private final static long addend = 0xBL;
071 private final static long mask = (1L << 48) - 1;
072
073 /**
074 * Creates a new random number generator. This constructor sets
075 * the seed of the random number generator to a value very likely
076 * to be distinct from any other invocation of this constructor.
077 */
078 public Random() {
079 this (++seedUniquifier + System.nanoTime());
080 }
081
082 private static volatile long seedUniquifier = 8682522807148012L;
083
084 /**
085 * Creates a new random number generator using a single {@code long} seed.
086 * The seed is the initial value of the internal state of the pseudorandom
087 * number generator which is maintained by method {@link #next}.
088 *
089 * <p>The invocation {@code new Random(seed)} is equivalent to:
090 * <pre> {@code
091 * Random rnd = new Random();
092 * rnd.setSeed(seed);}</pre>
093 *
094 * @param seed the initial seed
095 * @see #setSeed(long)
096 */
097 public Random(long seed) {
098 this .seed = new AtomicLong(0L);
099 setSeed(seed);
100 }
101
102 /**
103 * Sets the seed of this random number generator using a single
104 * {@code long} seed. The general contract of {@code setSeed} is
105 * that it alters the state of this random number generator object
106 * so as to be in exactly the same state as if it had just been
107 * created with the argument {@code seed} as a seed. The method
108 * {@code setSeed} is implemented by class {@code Random} by
109 * atomically updating the seed to
110 * <pre>{@code (seed ^ 0x5DEECE66DL) & ((1L << 48) - 1)}</pre>
111 * and clearing the {@code haveNextNextGaussian} flag used by {@link
112 * #nextGaussian}.
113 *
114 * <p>The implementation of {@code setSeed} by class {@code Random}
115 * happens to use only 48 bits of the given seed. In general, however,
116 * an overriding method may use all 64 bits of the {@code long}
117 * argument as a seed value.
118 *
119 * @param seed the initial seed
120 */
121 synchronized public void setSeed(long seed) {
122 seed = (seed ^ multiplier) & mask;
123 this .seed.set(seed);
124 haveNextNextGaussian = false;
125 }
126
127 /**
128 * Generates the next pseudorandom number. Subclasses should
129 * override this, as this is used by all other methods.
130 *
131 * <p>The general contract of {@code next} is that it returns an
132 * {@code int} value and if the argument {@code bits} is between
133 * {@code 1} and {@code 32} (inclusive), then that many low-order
134 * bits of the returned value will be (approximately) independently
135 * chosen bit values, each of which is (approximately) equally
136 * likely to be {@code 0} or {@code 1}. The method {@code next} is
137 * implemented by class {@code Random} by atomically updating the seed to
138 * <pre>{@code (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1)}</pre>
139 * and returning
140 * <pre>{@code (int)(seed >>> (48 - bits))}.</pre>
141 *
142 * This is a linear congruential pseudorandom number generator, as
143 * defined by D. H. Lehmer and described by Donald E. Knuth in
144 * <i>The Art of Computer Programming,</i> Volume 3:
145 * <i>Seminumerical Algorithms</i>, section 3.2.1.
146 *
147 * @param bits random bits
148 * @return the next pseudorandom value from this random number
149 * generator's sequence
150 * @since 1.1
151 */
152 protected int next(int bits) {
153 long oldseed, nextseed;
154 AtomicLong seed = this .seed;
155 do {
156 oldseed = seed.get();
157 nextseed = (oldseed * multiplier + addend) & mask;
158 } while (!seed.compareAndSet(oldseed, nextseed));
159 return (int) (nextseed >>> (48 - bits));
160 }
161
162 /**
163 * Generates random bytes and places them into a user-supplied
164 * byte array. The number of random bytes produced is equal to
165 * the length of the byte array.
166 *
167 * <p>The method {@code nextBytes} is implemented by class {@code Random}
168 * as if by:
169 * <pre> {@code
170 * public void nextBytes(byte[] bytes) {
171 * for (int i = 0; i < bytes.length; )
172 * for (int rnd = nextInt(), n = Math.min(bytes.length - i, 4);
173 * n-- > 0; rnd >>= 8)
174 * bytes[i++] = (byte)rnd;
175 * }}</pre>
176 *
177 * @param bytes the byte array to fill with random bytes
178 * @throws NullPointerException if the byte array is null
179 * @since 1.1
180 */
181 public void nextBytes(byte[] bytes) {
182 for (int i = 0, len = bytes.length; i < len;)
183 for (int rnd = nextInt(), n = Math.min(len - i,
184 Integer.SIZE / Byte.SIZE); n-- > 0; rnd >>= Byte.SIZE)
185 bytes[i++] = (byte) rnd;
186 }
187
188 /**
189 * Returns the next pseudorandom, uniformly distributed {@code int}
190 * value from this random number generator's sequence. The general
191 * contract of {@code nextInt} is that one {@code int} value is
192 * pseudorandomly generated and returned. All 2<font size="-1"><sup>32
193 * </sup></font> possible {@code int} values are produced with
194 * (approximately) equal probability.
195 *
196 * <p>The method {@code nextInt} is implemented by class {@code Random}
197 * as if by:
198 * <pre> {@code
199 * public int nextInt() {
200 * return next(32);
201 * }}</pre>
202 *
203 * @return the next pseudorandom, uniformly distributed {@code int}
204 * value from this random number generator's sequence
205 */
206 public int nextInt() {
207 return next(32);
208 }
209
210 /**
211 * Returns a pseudorandom, uniformly distributed {@code int} value
212 * between 0 (inclusive) and the specified value (exclusive), drawn from
213 * this random number generator's sequence. The general contract of
214 * {@code nextInt} is that one {@code int} value in the specified range
215 * is pseudorandomly generated and returned. All {@code n} possible
216 * {@code int} values are produced with (approximately) equal
217 * probability. The method {@code nextInt(int n)} is implemented by
218 * class {@code Random} as if by:
219 * <pre> {@code
220 * public int nextInt(int n) {
221 * if (n <= 0)
222 * throw new IllegalArgumentException("n must be positive");
223 *
224 * if ((n & -n) == n) // i.e., n is a power of 2
225 * return (int)((n * (long)next(31)) >> 31);
226 *
227 * int bits, val;
228 * do {
229 * bits = next(31);
230 * val = bits % n;
231 * } while (bits - val + (n-1) < 0);
232 * return val;
233 * }}</pre>
234 *
235 * <p>The hedge "approximately" is used in the foregoing description only
236 * because the next method is only approximately an unbiased source of
237 * independently chosen bits. If it were a perfect source of randomly
238 * chosen bits, then the algorithm shown would choose {@code int}
239 * values from the stated range with perfect uniformity.
240 * <p>
241 * The algorithm is slightly tricky. It rejects values that would result
242 * in an uneven distribution (due to the fact that 2^31 is not divisible
243 * by n). The probability of a value being rejected depends on n. The
244 * worst case is n=2^30+1, for which the probability of a reject is 1/2,
245 * and the expected number of iterations before the loop terminates is 2.
246 * <p>
247 * The algorithm treats the case where n is a power of two specially: it
248 * returns the correct number of high-order bits from the underlying
249 * pseudo-random number generator. In the absence of special treatment,
250 * the correct number of <i>low-order</i> bits would be returned. Linear
251 * congruential pseudo-random number generators such as the one
252 * implemented by this class are known to have short periods in the
253 * sequence of values of their low-order bits. Thus, this special case
254 * greatly increases the length of the sequence of values returned by
255 * successive calls to this method if n is a small power of two.
256 *
257 * @param n the bound on the random number to be returned. Must be
258 * positive.
259 * @return the next pseudorandom, uniformly distributed {@code int}
260 * value between {@code 0} (inclusive) and {@code n} (exclusive)
261 * from this random number generator's sequence
262 * @exception IllegalArgumentException if n is not positive
263 * @since 1.2
264 */
265
266 public int nextInt(int n) {
267 if (n <= 0)
268 throw new IllegalArgumentException("n must be positive");
269
270 if ((n & -n) == n) // i.e., n is a power of 2
271 return (int) ((n * (long) next(31)) >> 31);
272
273 int bits, val;
274 do {
275 bits = next(31);
276 val = bits % n;
277 } while (bits - val + (n - 1) < 0);
278 return val;
279 }
280
281 /**
282 * Returns the next pseudorandom, uniformly distributed {@code long}
283 * value from this random number generator's sequence. The general
284 * contract of {@code nextLong} is that one {@code long} value is
285 * pseudorandomly generated and returned.
286 *
287 * <p>The method {@code nextLong} is implemented by class {@code Random}
288 * as if by:
289 * <pre> {@code
290 * public long nextLong() {
291 * return ((long)next(32) << 32) + next(32);
292 * }}</pre>
293 *
294 * Because class {@code Random} uses a seed with only 48 bits,
295 * this algorithm will not return all possible {@code long} values.
296 *
297 * @return the next pseudorandom, uniformly distributed {@code long}
298 * value from this random number generator's sequence
299 */
300 public long nextLong() {
301 // it's okay that the bottom word remains signed.
302 return ((long) (next(32)) << 32) + next(32);
303 }
304
305 /**
306 * Returns the next pseudorandom, uniformly distributed
307 * {@code boolean} value from this random number generator's
308 * sequence. The general contract of {@code nextBoolean} is that one
309 * {@code boolean} value is pseudorandomly generated and returned. The
310 * values {@code true} and {@code false} are produced with
311 * (approximately) equal probability.
312 *
313 * <p>The method {@code nextBoolean} is implemented by class {@code Random}
314 * as if by:
315 * <pre> {@code
316 * public boolean nextBoolean() {
317 * return next(1) != 0;
318 * }}</pre>
319 *
320 * @return the next pseudorandom, uniformly distributed
321 * {@code boolean} value from this random number generator's
322 * sequence
323 * @since 1.2
324 */
325 public boolean nextBoolean() {
326 return next(1) != 0;
327 }
328
329 /**
330 * Returns the next pseudorandom, uniformly distributed {@code float}
331 * value between {@code 0.0} and {@code 1.0} from this random
332 * number generator's sequence.
333 *
334 * <p>The general contract of {@code nextFloat} is that one
335 * {@code float} value, chosen (approximately) uniformly from the
336 * range {@code 0.0f} (inclusive) to {@code 1.0f} (exclusive), is
337 * pseudorandomly generated and returned. All 2<font
338 * size="-1"><sup>24</sup></font> possible {@code float} values
339 * of the form <i>m x </i>2<font
340 * size="-1"><sup>-24</sup></font>, where <i>m</i> is a positive
341 * integer less than 2<font size="-1"><sup>24</sup> </font>, are
342 * produced with (approximately) equal probability.
343 *
344 * <p>The method {@code nextFloat} is implemented by class {@code Random}
345 * as if by:
346 * <pre> {@code
347 * public float nextFloat() {
348 * return next(24) / ((float)(1 << 24));
349 * }}</pre>
350 *
351 * <p>The hedge "approximately" is used in the foregoing description only
352 * because the next method is only approximately an unbiased source of
353 * independently chosen bits. If it were a perfect source of randomly
354 * chosen bits, then the algorithm shown would choose {@code float}
355 * values from the stated range with perfect uniformity.<p>
356 * [In early versions of Java, the result was incorrectly calculated as:
357 * <pre> {@code
358 * return next(30) / ((float)(1 << 30));}</pre>
359 * This might seem to be equivalent, if not better, but in fact it
360 * introduced a slight nonuniformity because of the bias in the rounding
361 * of floating-point numbers: it was slightly more likely that the
362 * low-order bit of the significand would be 0 than that it would be 1.]
363 *
364 * @return the next pseudorandom, uniformly distributed {@code float}
365 * value between {@code 0.0} and {@code 1.0} from this
366 * random number generator's sequence
367 */
368 public float nextFloat() {
369 return next(24) / ((float) (1 << 24));
370 }
371
372 /**
373 * Returns the next pseudorandom, uniformly distributed
374 * {@code double} value between {@code 0.0} and
375 * {@code 1.0} from this random number generator's sequence.
376 *
377 * <p>The general contract of {@code nextDouble} is that one
378 * {@code double} value, chosen (approximately) uniformly from the
379 * range {@code 0.0d} (inclusive) to {@code 1.0d} (exclusive), is
380 * pseudorandomly generated and returned.
381 *
382 * <p>The method {@code nextDouble} is implemented by class {@code Random}
383 * as if by:
384 * <pre> {@code
385 * public double nextDouble() {
386 * return (((long)next(26) << 27) + next(27))
387 * / (double)(1L << 53);
388 * }}</pre>
389 *
390 * <p>The hedge "approximately" is used in the foregoing description only
391 * because the {@code next} method is only approximately an unbiased
392 * source of independently chosen bits. If it were a perfect source of
393 * randomly chosen bits, then the algorithm shown would choose
394 * {@code double} values from the stated range with perfect uniformity.
395 * <p>[In early versions of Java, the result was incorrectly calculated as:
396 * <pre> {@code
397 * return (((long)next(27) << 27) + next(27))
398 * / (double)(1L << 54);}</pre>
399 * This might seem to be equivalent, if not better, but in fact it
400 * introduced a large nonuniformity because of the bias in the rounding
401 * of floating-point numbers: it was three times as likely that the
402 * low-order bit of the significand would be 0 than that it would be 1!
403 * This nonuniformity probably doesn't matter much in practice, but we
404 * strive for perfection.]
405 *
406 * @return the next pseudorandom, uniformly distributed {@code double}
407 * value between {@code 0.0} and {@code 1.0} from this
408 * random number generator's sequence
409 * @see Math#random
410 */
411 public double nextDouble() {
412 return (((long) (next(26)) << 27) + next(27))
413 / (double) (1L << 53);
414 }
415
416 private double nextNextGaussian;
417 private boolean haveNextNextGaussian = false;
418
419 /**
420 * Returns the next pseudorandom, Gaussian ("normally") distributed
421 * {@code double} value with mean {@code 0.0} and standard
422 * deviation {@code 1.0} from this random number generator's sequence.
423 * <p>
424 * The general contract of {@code nextGaussian} is that one
425 * {@code double} value, chosen from (approximately) the usual
426 * normal distribution with mean {@code 0.0} and standard deviation
427 * {@code 1.0}, is pseudorandomly generated and returned.
428 *
429 * <p>The method {@code nextGaussian} is implemented by class
430 * {@code Random} as if by a threadsafe version of the following:
431 * <pre> {@code
432 * private double nextNextGaussian;
433 * private boolean haveNextNextGaussian = false;
434 *
435 * public double nextGaussian() {
436 * if (haveNextNextGaussian) {
437 * haveNextNextGaussian = false;
438 * return nextNextGaussian;
439 * } else {
440 * double v1, v2, s;
441 * do {
442 * v1 = 2 * nextDouble() - 1; // between -1.0 and 1.0
443 * v2 = 2 * nextDouble() - 1; // between -1.0 and 1.0
444 * s = v1 * v1 + v2 * v2;
445 * } while (s >= 1 || s == 0);
446 * double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s);
447 * nextNextGaussian = v2 * multiplier;
448 * haveNextNextGaussian = true;
449 * return v1 * multiplier;
450 * }
451 * }}</pre>
452 * This uses the <i>polar method</i> of G. E. P. Box, M. E. Muller, and
453 * G. Marsaglia, as described by Donald E. Knuth in <i>The Art of
454 * Computer Programming</i>, Volume 3: <i>Seminumerical Algorithms</i>,
455 * section 3.4.1, subsection C, algorithm P. Note that it generates two
456 * independent values at the cost of only one call to {@code StrictMath.log}
457 * and one call to {@code StrictMath.sqrt}.
458 *
459 * @return the next pseudorandom, Gaussian ("normally") distributed
460 * {@code double} value with mean {@code 0.0} and
461 * standard deviation {@code 1.0} from this random number
462 * generator's sequence
463 */
464 synchronized public double nextGaussian() {
465 // See Knuth, ACP, Section 3.4.1 Algorithm C.
466 if (haveNextNextGaussian) {
467 haveNextNextGaussian = false;
468 return nextNextGaussian;
469 } else {
470 double v1, v2, s;
471 do {
472 v1 = 2 * nextDouble() - 1; // between -1 and 1
473 v2 = 2 * nextDouble() - 1; // between -1 and 1
474 s = v1 * v1 + v2 * v2;
475 } while (s >= 1 || s == 0);
476 double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)
477 / s);
478 nextNextGaussian = v2 * multiplier;
479 haveNextNextGaussian = true;
480 return v1 * multiplier;
481 }
482 }
483
484 /**
485 * Serializable fields for Random.
486 *
487 * @serialField seed long
488 * seed for random computations
489 * @serialField nextNextGaussian double
490 * next Gaussian to be returned
491 * @serialField haveNextNextGaussian boolean
492 * nextNextGaussian is valid
493 */
494 private static final ObjectStreamField[] serialPersistentFields = {
495 new ObjectStreamField("seed", Long.TYPE),
496 new ObjectStreamField("nextNextGaussian", Double.TYPE),
497 new ObjectStreamField("haveNextNextGaussian", Boolean.TYPE) };
498
499 /**
500 * Reconstitute the {@code Random} instance from a stream (that is,
501 * deserialize it).
502 */
503 private void readObject(java.io.ObjectInputStream s)
504 throws java.io.IOException, ClassNotFoundException {
505
506 ObjectInputStream.GetField fields = s.readFields();
507
508 // The seed is read in as {@code long} for
509 // historical reasons, but it is converted to an AtomicLong.
510 long seedVal = (long) fields.get("seed", -1L);
511 if (seedVal < 0)
512 throw new java.io.StreamCorruptedException(
513 "Random: invalid seed");
514 resetSeed(seedVal);
515 nextNextGaussian = fields.get("nextNextGaussian", 0.0);
516 haveNextNextGaussian = fields
517 .get("haveNextNextGaussian", false);
518 }
519
520 /**
521 * Save the {@code Random} instance to a stream.
522 */
523 synchronized private void writeObject(ObjectOutputStream s)
524 throws IOException {
525
526 // set the values of the Serializable fields
527 ObjectOutputStream.PutField fields = s.putFields();
528
529 // The seed is serialized as a long for historical reasons.
530 fields.put("seed", seed.get());
531 fields.put("nextNextGaussian", nextNextGaussian);
532 fields.put("haveNextNextGaussian", haveNextNextGaussian);
533
534 // save them
535 s.writeFields();
536 }
537
538 // Support for resetting seed while deserializing
539 private static final Unsafe unsafe = Unsafe.getUnsafe();
540 private static final long seedOffset;
541 static {
542 try {
543 seedOffset = unsafe.objectFieldOffset(Random.class
544 .getDeclaredField("seed"));
545 } catch (Exception ex) {
546 throw new Error(ex);
547 }
548 }
549
550 private void resetSeed(long seedVal) {
551 unsafe.putObjectVolatile(this , seedOffset, new AtomicLong(
552 seedVal));
553 }
554 }
|