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