ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/Random.java
Revision: 1.2
Committed: Fri Aug 8 20:05:07 2003 UTC (20 years, 9 months ago) by tim
Branch: MAIN
Changes since 1.1: +1 -2 lines
Log Message:
Scrunched catch, finally, else clauses.

File Contents

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