ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/Random.java
(Generate patch)

Comparing jsr166/src/main/java/util/Random.java (file contents):
Revision 1.7 by jsr166, Sun Apr 11 04:50:24 2004 UTC vs.
Revision 1.11 by jsr166, Sun Oct 2 07:10:59 2005 UTC

# Line 1 | Line 1
1   /*
2   * %W% %E%
3   *
4 < * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
4 > * Copyright 2005 Sun Microsystems, Inc. All rights reserved.
5   * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6   */
7  
# Line 10 | Line 10 | 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.)
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
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
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
32 > * Many applications will find the <code>random</code> method in
33   * class <code>Math</code> simpler to use.
34   *
35   * @author  Frank Yellin
# Line 63 | Line 63 | class Random implements java.io.Serializ
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
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
71 >     * Used by method <tt>next</tt> to hold
72       * the state of the pseudorandom number generator.
73       *
74       * @param   seed   the initial seed.
# Line 80 | Line 80 | class Random implements java.io.Serializ
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 <     * Note: Although the seed value is an AtomicLong, this method
100 <     *       must still be synchronized to ensure correct semantics
101 <     *       of haveNextNextGaussian.
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       */
# Line 110 | Line 104 | class Random implements java.io.Serializ
104  
105      /**
106       * Generates the next pseudorandom number. Subclass should
107 <     * override this, as this is used by all other methods.<p>
108 <     * The general contract of <tt>next</tt> is that it returns an
109 <     * <tt>int</tt> value and if the argument bits is between <tt>1</tt>
110 <     * and <tt>32</tt> (inclusive), then that many low-order bits of the
111 <     * returned value will be (approximately) independently chosen bit
112 <     * values, each of which is (approximately) equally likely to be
113 <     * <tt>0</tt> or <tt>1</tt>. The method <tt>next</tt> is implemented
114 <     * by class <tt>Random</tt> as follows:
115 <     * <blockquote><pre>
116 <     * synchronized protected int next(int bits) {
117 <     *       seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1);
118 <     *       return (int)(seed >>> (48 - bits));
119 <     * }</pre></blockquote>
120 <     * 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
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
# Line 136 | Line 128 | class Random implements java.io.Serializ
128          long oldseed, nextseed;
129          AtomicLong seed = this.seed;
130          do {
131 <            oldseed = seed.get();
132 <            nextseed = (oldseed * multiplier + addend) & mask;
131 >            oldseed = seed.get();
132 >            nextseed = (oldseed * multiplier + addend) & mask;
133          } while (!seed.compareAndSet(oldseed, nextseed));
134          return (int)(nextseed >>> (48 - bits));
135      }
# Line 146 | Line 138 | class Random implements java.io.Serializ
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
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
144 >     *
145 >     * @param bytes  the non-null byte array in which to put the
146       *               random bytes.
147       * @since   JDK1.1
148       */
# Line 173 | Line 165 | class Random implements java.io.Serializ
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
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
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>
# Line 213 | Line 205 | class Random implements java.io.Serializ
205       * }
206       * </pre></blockquote>
207       * <p>
208 <     * The hedge "approximately" is used in the foregoing description only
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>
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
# Line 260 | Line 252 | class Random implements java.io.Serializ
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
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() {
# Line 301 | Line 293 | class Random implements java.io.Serializ
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>
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&nbsp;x&nbsp</i>2<font size="-1"><sup>-24</sup></font>, where
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&nbsp;x&nbsp</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
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>
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.]
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
# Line 338 | Line 330 | class Random implements java.io.Serializ
330      }
331  
332      /**
333 <     * Returns the next pseudorandom, uniformly distributed
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>
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&nbsp;x&nbsp;</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
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.
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
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.]
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
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       */
# Line 389 | Line 381 | class Random implements java.io.Serializ
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 follows:
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 <     * synchronized public double nextGaussian() {
391 >     * public double nextGaussian() {
392       *    if (haveNextNextGaussian) {
393       *            haveNextNextGaussian = false;
394       *            return nextNextGaussian;
395       *    } else {
396       *            double v1, v2, s;
397 <     *            do {
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 = Math.sqrt(-2 * Math.log(s)/s);
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>,
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>Math.log</tt>
413 <     * and one call to <tt>Math.sqrt</tt>.
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
# Line 431 | Line 424 | class Random implements java.io.Serializ
424              return nextNextGaussian;
425          } else {
426              double v1, v2, s;
427 <            do {
427 >            do {
428                  v1 = 2 * nextDouble() - 1; // between -1 and 1
429 <                v2 = 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 = Math.sqrt(-2 * Math.log(s)/s);
432 >            double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s);
433              nextNextGaussian = v2 * multiplier;
434              haveNextNextGaussian = true;
435              return v1 * multiplier;
# Line 498 | Line 491 | class Random implements java.io.Serializ
491  
492      }
493  
494 < }    
494 > }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines