ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/Random.java
Revision: 1.5
Committed: Mon Nov 17 08:19:58 2003 UTC (20 years, 6 months ago) by jozart
Branch: MAIN
CVS Tags: JSR166_DEC9_PRE_ES_SUBMIT, JSR166_DEC9_POST_ES_SUBMIT
Changes since 1.4: +2 -2 lines
Log Message:
Fixed indentation inside do-while in next(bits) method.

File Contents

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