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.19 by jsr166, Tue Jan 30 03:46:41 2007 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines