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.4 by jsr166, Fri Nov 7 01:36:42 2003 UTC vs.
Revision 1.14 by dl, Thu Feb 2 20:09:07 2006 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines