ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/Random.java
Revision: 1.3
Committed: Mon Aug 25 18:33:04 2003 UTC (20 years, 9 months ago) by dl
Branch: MAIN
CVS Tags: JSR166_NOV3_FREEZE
Changes since 1.2: +13 -22 lines
Log Message:
Serial ids; re-checkin in Random using j.u.c.aAtomicLong

File Contents

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