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.2 by tim, Fri Aug 8 20:05:07 2003 UTC vs.
Revision 1.21 by jsr166, Sun May 18 23:47:56 2008 UTC

# Line 1 | Line 1
1   /*
2 < * @(#)Random.java      1.38 02/03/04
2 > * Copyright 1995-2007 Sun Microsystems, Inc.  All Rights Reserved.
3 > * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4   *
5 < * Copyright 2002 Sun Microsystems, Inc. All rights reserved.
6 < * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
5 > * This code is free software; you can redistribute it and/or modify it
6 > * under the terms of the GNU General Public License version 2 only, as
7 > * published by the Free Software Foundation.  Sun designates this
8 > * particular file as subject to the "Classpath" exception as provided
9 > * by Sun in the LICENSE file that accompanied this code.
10 > *
11 > * This code is distributed in the hope that it will be useful, but WITHOUT
12 > * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 > * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 > * version 2 for more details (a copy is included in the LICENSE file that
15 > * accompanied this code).
16 > *
17 > * You should have received a copy of the GNU General Public License version
18 > * 2 along with this work; if not, write to the Free Software Foundation,
19 > * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 > *
21 > * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
22 > * CA 95054 USA or visit www.sun.com if you need additional information or
23 > * have any questions.
24   */
25  
26   package java.util;
27   import java.io.*;
28 + import java.util.concurrent.atomic.AtomicLong;
29   import sun.misc.Unsafe;
30  
31   /**
32 < * An instance of this class is used to generate a stream of
33 < * pseudorandom numbers. The class uses a 48-bit seed, which is
34 < * modified using a linear congruential formula. (See Donald Knuth,
35 < * <i>The Art of Computer Programming, Volume 2</i>, Section 3.2.1.)
32 > * An instance of this class is used to generate a stream of
33 > * pseudorandom numbers. The class uses a 48-bit seed, which is
34 > * modified using a linear congruential formula. (See Donald Knuth,
35 > * <i>The Art of Computer Programming, Volume 3</i>, Section 3.2.1.)
36   * <p>
37 < * If two instances of <code>Random</code> are created with the same
38 < * seed, and the same sequence of method calls is made for each, they
39 < * will generate and return identical sequences of numbers. In order to
40 < * guarantee this property, particular algorithms are specified for the
41 < * class <tt>Random</tt>. Java implementations must use all the algorithms
42 < * shown here for the class <tt>Random</tt>, for the sake of absolute
43 < * portability of Java code. However, subclasses of class <tt>Random</tt>
44 < * are permitted to use other algorithms, so long as they adhere to the
37 > * If two instances of {@code Random} are created with the same
38 > * seed, and the same sequence of method calls is made for each, they
39 > * will generate and return identical sequences of numbers. In order to
40 > * guarantee this property, particular algorithms are specified for the
41 > * class {@code Random}. Java implementations must use all the algorithms
42 > * shown here for the class {@code Random}, for the sake of absolute
43 > * portability of Java code. However, subclasses of class {@code Random}
44 > * are permitted to use other algorithms, so long as they adhere to the
45   * general contracts for all the methods.
46   * <p>
47 < * The algorithms implemented by class <tt>Random</tt> use a
48 < * <tt>protected</tt> utility method that on each invocation can supply
47 > * The algorithms implemented by class {@code Random} use a
48 > * {@code protected} utility method that on each invocation can supply
49   * up to 32 pseudorandomly generated bits.
50   * <p>
51 < * Many applications will find the <code>random</code> method in
33 < * class <code>Math</code> simpler to use.
51 > * Many applications will find the method {@link Math#random} simpler to use.
52   *
53   * @author  Frank Yellin
54 < * @version 1.38, 03/04/02
55 < * @see     java.lang.Math#random()
38 < * @since   JDK1.0
54 > * @version %I%, %G%
55 > * @since   1.0
56   */
57   public
58   class Random implements java.io.Serializable {
59      /** use serialVersionUID from JDK 1.1 for interoperability */
60      static final long serialVersionUID = 3905348978240129619L;
61  
45    // Setup to use Unsafe.compareAndSwapLong to update seed.
46    private static final Unsafe unsafe =  Unsafe.getUnsafe();
47    private static final long seedOffset;
48    static {
49      try {
50        seedOffset =
51          unsafe.objectFieldOffset(Random.class.getDeclaredField("seed"));
52      } catch(Exception ex) { throw new Error(ex); }
53    }
54
62      /**
63       * The internal state associated with this pseudorandom number generator.
64       * (The specs for the methods in this class describe the ongoing
65       * computation of this value.)
59     *
60     * @serial
66       */
67 <    private volatile long seed;
67 >    private final AtomicLong seed;
68  
69      private final static long multiplier = 0x5DEECE66DL;
70      private final static long addend = 0xBL;
71      private final static long mask = (1L << 48) - 1;
72  
73 <    /**
74 <     * Creates a new random number generator. Its seed is initialized to
75 <     * a value based on the current time:
76 <     * <blockquote><pre>
77 <     * public Random() { this(System.currentTimeMillis()); }</pre></blockquote>
78 <     * Two Random objects created within the same millisecond will have
79 <     * the same sequence of random numbers.
80 <     *
81 <     * @see     java.lang.System#currentTimeMillis()
82 <     */
83 <    public Random() { this(System.currentTimeMillis()); }
84 <
85 <    /**
86 <     * Creates a new random number generator using a single
87 <     * <code>long</code> seed:
88 <     * <blockquote><pre>
89 <     * public Random(long seed) { setSeed(seed); }</pre></blockquote>
85 <     * Used by method <tt>next</tt> to hold
86 <     * the state of the pseudorandom number generator.
73 >    /**
74 >     * Creates a new random number generator. This constructor sets
75 >     * the seed of the random number generator to a value very likely
76 >     * to be distinct from any other invocation of this constructor.
77 >     */
78 >    public Random() { this(++seedUniquifier + System.nanoTime()); }
79 >    private static volatile long seedUniquifier = 8682522807148012L;
80 >
81 >    /**
82 >     * Creates a new random number generator using a single {@code long} seed.
83 >     * The seed is the initial value of the internal state of the pseudorandom
84 >     * number generator which is maintained by method {@link #next}.
85 >     *
86 >     * <p>The invocation {@code new Random(seed)} is equivalent to:
87 >     *  <pre> {@code
88 >     * Random rnd = new Random();
89 >     * rnd.setSeed(seed);}</pre>
90       *
91 <     * @param   seed   the initial seed.
92 <     * @see     java.util.Random#setSeed(long)
91 >     * @param seed the initial seed
92 >     * @see   #setSeed(long)
93       */
94      public Random(long seed) {
95 +        this.seed = new AtomicLong(0L);
96          setSeed(seed);
97      }
98  
99      /**
100 <     * Sets the seed of this random number generator using a single
101 <     * <code>long</code> seed. The general contract of <tt>setSeed</tt>
102 <     * is that it alters the state of this random number generator
103 <     * object so as to be in exactly the same state as if it had just
104 <     * been created with the argument <tt>seed</tt> as a seed. The method
105 <     * <tt>setSeed</tt> is implemented by class Random as follows:
106 <     * <blockquote><pre>
107 <     * synchronized public void setSeed(long seed) {
108 <     *       this.seed = (seed ^ 0x5DEECE66DL) & ((1L << 48) - 1);
109 <     *       haveNextNextGaussian = false;
110 <     * }</pre></blockquote>
111 <     * The implementation of <tt>setSeed</tt> by class <tt>Random</tt>
112 <     * happens to use only 48 bits of the given seed. In general, however,
113 <     * an overriding method may use all 64 bits of the long argument
114 <     * as a seed value.
111 <     *
112 <     * Note: Even though seed is updated atomically, this method
113 <     *       must still be synchronized to ensure correct semantics
114 <     *       of haveNextNextGaussian.
100 >     * Sets the seed of this random number generator using a single
101 >     * {@code long} seed. The general contract of {@code setSeed} is
102 >     * that it alters the state of this random number generator object
103 >     * so as to be in exactly the same state as if it had just been
104 >     * created with the argument {@code seed} as a seed. The method
105 >     * {@code setSeed} is implemented by class {@code Random} by
106 >     * atomically updating the seed to
107 >     *  <pre>{@code (seed ^ 0x5DEECE66DL) & ((1L << 48) - 1)}</pre>
108 >     * and clearing the {@code haveNextNextGaussian} flag used by {@link
109 >     * #nextGaussian}.
110 >     *
111 >     * <p>The implementation of {@code setSeed} by class {@code Random}
112 >     * happens to use only 48 bits of the given seed. In general, however,
113 >     * an overriding method may use all 64 bits of the {@code long}
114 >     * argument as a seed value.
115       *
116 <     * @param   seed   the initial seed.
116 >     * @param seed the initial seed
117       */
118      synchronized public void setSeed(long seed) {
119 <        this.seed = (seed ^ multiplier) & mask;
120 <        haveNextNextGaussian = false;
119 >        seed = (seed ^ multiplier) & mask;
120 >        this.seed.set(seed);
121 >        haveNextNextGaussian = false;
122      }
123  
124      /**
125 <     * Generates the next pseudorandom number. Subclass should
126 <     * override this, as this is used by all other methods.<p>
127 <     * The general contract of <tt>next</tt> is that it returns an
128 <     * <tt>int</tt> value and if the argument bits is between <tt>1</tt>
129 <     * and <tt>32</tt> (inclusive), then that many low-order bits of the
130 <     * returned value will be (approximately) independently chosen bit
131 <     * values, each of which is (approximately) equally likely to be
132 <     * <tt>0</tt> or <tt>1</tt>. The method <tt>next</tt> is implemented
133 <     * by class <tt>Random</tt> as follows:
134 <     * <blockquote><pre>
135 <     * synchronized protected int next(int bits) {
136 <     *       seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1);
137 <     *       return (int)(seed >>> (48 - bits));
138 <     * }</pre></blockquote>
139 <     * This is a linear congruential pseudorandom number generator, as
140 <     * defined by D. H. Lehmer and described by Donald E. Knuth in <i>The
141 <     * Art of Computer Programming,</i> Volume 2: <i>Seminumerical
142 <     * Algorithms</i>, section 3.2.1.
143 <     *
144 <     * @param   bits random bits
145 <     * @return  the next pseudorandom value from this random number generator's sequence.
146 <     * @since   JDK1.1
125 >     * Generates the next pseudorandom number. Subclasses should
126 >     * override this, as this is used by all other methods.
127 >     *
128 >     * <p>The general contract of {@code next} is that it returns an
129 >     * {@code int} value and if the argument {@code bits} is between
130 >     * {@code 1} and {@code 32} (inclusive), then that many low-order
131 >     * bits of the returned value will be (approximately) independently
132 >     * chosen bit values, each of which is (approximately) equally
133 >     * likely to be {@code 0} or {@code 1}. The method {@code next} is
134 >     * implemented by class {@code Random} by atomically updating the seed to
135 >     *  <pre>{@code (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1)}</pre>
136 >     * and returning
137 >     *  <pre>{@code (int)(seed >>> (48 - bits))}.</pre>
138 >     *
139 >     * This is a linear congruential pseudorandom number generator, as
140 >     * defined by D. H. Lehmer and described by Donald E. Knuth in
141 >     * <i>The Art of Computer Programming,</i> Volume 3:
142 >     * <i>Seminumerical Algorithms</i>, section 3.2.1.
143 >     *
144 >     * @param  bits random bits
145 >     * @return the next pseudorandom value from this random number
146 >     *         generator's sequence
147 >     * @since  1.1
148       */
149      protected int next(int bits) {
150          long oldseed, nextseed;
151 +        AtomicLong seed = this.seed;
152          do {
153 <          oldseed = seed;
154 <          nextseed = (oldseed * multiplier + addend) & mask;
155 <        } while (!unsafe.compareAndSwapLong(this, seedOffset,
153 <                                           oldseed, nextseed));
153 >            oldseed = seed.get();
154 >            nextseed = (oldseed * multiplier + addend) & mask;
155 >        } while (!seed.compareAndSet(oldseed, nextseed));
156          return (int)(nextseed >>> (48 - bits));
157      }
158  
157    private static final int BITS_PER_BYTE = 8;
158    private static final int BYTES_PER_INT = 4;
159
159      /**
160 <     * Generates random bytes and places them into a user-supplied
161 <     * byte array.  The number of random bytes produced is equal to
160 >     * Generates random bytes and places them into a user-supplied
161 >     * byte array.  The number of random bytes produced is equal to
162       * the length of the byte array.
163 <     *
164 <     * @param bytes  the non-null byte array in which to put the
165 <     *               random bytes.
166 <     * @since   JDK1.1
163 >     *
164 >     * <p>The method {@code nextBytes} is implemented by class {@code Random}
165 >     * as if by:
166 >     *  <pre> {@code
167 >     * public void nextBytes(byte[] bytes) {
168 >     *   for (int i = 0; i < bytes.length; )
169 >     *     for (int rnd = nextInt(), n = Math.min(bytes.length - i, 4);
170 >     *          n-- > 0; rnd >>= 8)
171 >     *       bytes[i++] = (byte)rnd;
172 >     * }}</pre>
173 >     *
174 >     * @param  bytes the byte array to fill with random bytes
175 >     * @throws NullPointerException if the byte array is null
176 >     * @since  1.1
177       */
178      public void nextBytes(byte[] bytes) {
179 <        int numRequested = bytes.length;
180 <
181 <        int numGot = 0, rnd = 0;
182 <
183 <        while (true) {
175 <            for (int i = 0; i < BYTES_PER_INT; i++) {
176 <                if (numGot == numRequested)
177 <                    return;
178 <
179 <                rnd = (i==0 ? next(BITS_PER_BYTE * BYTES_PER_INT)
180 <                            : rnd >> BITS_PER_BYTE);
181 <                bytes[numGot++] = (byte)rnd;
182 <            }
183 <        }
179 >        for (int i = 0, len = bytes.length; i < len; )
180 >            for (int rnd = nextInt(),
181 >                     n = Math.min(len - i, Integer.SIZE/Byte.SIZE);
182 >                 n-- > 0; rnd >>= Byte.SIZE)
183 >                bytes[i++] = (byte)rnd;
184      }
185  
186      /**
187 <     * Returns the next pseudorandom, uniformly distributed <code>int</code>
188 <     * value from this random number generator's sequence. The general
189 <     * contract of <tt>nextInt</tt> is that one <tt>int</tt> value is
187 >     * Returns the next pseudorandom, uniformly distributed {@code int}
188 >     * value from this random number generator's sequence. The general
189 >     * contract of {@code nextInt} is that one {@code int} value is
190       * pseudorandomly generated and returned. All 2<font size="-1"><sup>32
191 <     * </sup></font> possible <tt>int</tt> values are produced with
192 <     * (approximately) equal probability. The method <tt>nextInt</tt> is
193 <     * implemented by class <tt>Random</tt> as follows:
194 <     * <blockquote><pre>
195 <     * public int nextInt() {  return next(32); }</pre></blockquote>
191 >     * </sup></font> possible {@code int} values are produced with
192 >     * (approximately) equal probability.
193       *
194 <     * @return  the next pseudorandom, uniformly distributed <code>int</code>
195 <     *          value from this random number generator's sequence.
194 >     * <p>The method {@code nextInt} is implemented by class {@code Random}
195 >     * as if by:
196 >     *  <pre> {@code
197 >     * public int nextInt() {
198 >     *   return next(32);
199 >     * }}</pre>
200 >     *
201 >     * @return the next pseudorandom, uniformly distributed {@code int}
202 >     *         value from this random number generator's sequence
203       */
204 <    public int nextInt() {  return next(32); }
204 >    public int nextInt() {
205 >        return next(32);
206 >    }
207  
208      /**
209 <     * Returns a pseudorandom, uniformly distributed <tt>int</tt> value
209 >     * Returns a pseudorandom, uniformly distributed {@code int} value
210       * between 0 (inclusive) and the specified value (exclusive), drawn from
211       * this random number generator's sequence.  The general contract of
212 <     * <tt>nextInt</tt> is that one <tt>int</tt> value in the specified range
213 <     * is pseudorandomly generated and returned.  All <tt>n</tt> possible
214 <     * <tt>int</tt> values are produced with (approximately) equal
215 <     * probability.  The method <tt>nextInt(int n)</tt> is implemented by
216 <     * class <tt>Random</tt> as follows:
217 <     * <blockquote><pre>
212 >     * {@code nextInt} is that one {@code int} value in the specified range
213 >     * is pseudorandomly generated and returned.  All {@code n} possible
214 >     * {@code int} values are produced with (approximately) equal
215 >     * probability.  The method {@code nextInt(int n)} is implemented by
216 >     * class {@code Random} as if by:
217 >     *  <pre> {@code
218       * public int nextInt(int n) {
219 <     *     if (n<=0)
220 <     *          throw new IllegalArgumentException("n must be positive");
219 >     *   if (n <= 0)
220 >     *     throw new IllegalArgumentException("n must be positive");
221       *
222 <     *     if ((n & -n) == n)  // i.e., n is a power of 2
223 <     *         return (int)((n * (long)next(31)) >> 31);
222 >     *   if ((n & -n) == n)  // i.e., n is a power of 2
223 >     *     return (int)((n * (long)next(31)) >> 31);
224       *
225 <     *     int bits, val;
226 <     *     do {
227 <     *         bits = next(31);
228 <     *         val = bits % n;
229 <     *     } while(bits - val + (n-1) < 0);
230 <     *     return val;
231 <     * }
232 <     * </pre></blockquote>
233 <     * <p>
228 <     * The hedge "approximately" is used in the foregoing description only
225 >     *   int bits, val;
226 >     *   do {
227 >     *       bits = next(31);
228 >     *       val = bits % n;
229 >     *   } while (bits - val + (n-1) < 0);
230 >     *   return val;
231 >     * }}</pre>
232 >     *
233 >     * <p>The hedge "approximately" is used in the foregoing description only
234       * because the next method is only approximately an unbiased source of
235 <     * independently chosen bits.  If it were a perfect source of randomly
236 <     * chosen bits, then the algorithm shown would choose <tt>int</tt>
235 >     * independently chosen bits.  If it were a perfect source of randomly
236 >     * chosen bits, then the algorithm shown would choose {@code int}
237       * values from the stated range with perfect uniformity.
238       * <p>
239       * The algorithm is slightly tricky.  It rejects values that would result
# Line 248 | Line 253 | class Random implements java.io.Serializ
253       * successive calls to this method if n is a small power of two.
254       *
255       * @param n the bound on the random number to be returned.  Must be
256 <     *        positive.
257 <     * @return  a pseudorandom, uniformly distributed <tt>int</tt>
258 <     *          value between 0 (inclusive) and n (exclusive).
259 <     * @exception IllegalArgumentException n is not positive.
256 >     *        positive.
257 >     * @return the next pseudorandom, uniformly distributed {@code int}
258 >     *         value between {@code 0} (inclusive) and {@code n} (exclusive)
259 >     *         from this random number generator's sequence
260 >     * @exception IllegalArgumentException if n is not positive
261       * @since 1.2
262       */
263  
264      public int nextInt(int n) {
265 <        if (n<=0)
265 >        if (n <= 0)
266              throw new IllegalArgumentException("n must be positive");
267  
268          if ((n & -n) == n)  // i.e., n is a power of 2
# Line 266 | Line 272 | class Random implements java.io.Serializ
272          do {
273              bits = next(31);
274              val = bits % n;
275 <        } while(bits - val + (n-1) < 0);
275 >        } while (bits - val + (n-1) < 0);
276          return val;
277      }
278  
279      /**
280 <     * Returns the next pseudorandom, uniformly distributed <code>long</code>
281 <     * value from this random number generator's sequence. The general
282 <     * contract of <tt>nextLong</tt> is that one long value is pseudorandomly
283 <     * generated and returned. All 2<font size="-1"><sup>64</sup></font>
284 <     * possible <tt>long</tt> values are produced with (approximately) equal
285 <     * probability. The method <tt>nextLong</tt> is implemented by class
286 <     * <tt>Random</tt> as follows:
287 <     * <blockquote><pre>
280 >     * Returns the next pseudorandom, uniformly distributed {@code long}
281 >     * value from this random number generator's sequence. The general
282 >     * contract of {@code nextLong} is that one {@code long} value is
283 >     * pseudorandomly generated and returned.
284 >     *
285 >     * <p>The method {@code nextLong} is implemented by class {@code Random}
286 >     * as if by:
287 >     *  <pre> {@code
288       * public long nextLong() {
289 <     *       return ((long)next(32) << 32) + next(32);
290 <     * }</pre></blockquote>
289 >     *   return ((long)next(32) << 32) + next(32);
290 >     * }}</pre>
291       *
292 <     * @return  the next pseudorandom, uniformly distributed <code>long</code>
293 <     *          value from this random number generator's sequence.
292 >     * Because class {@code Random} uses a seed with only 48 bits,
293 >     * this algorithm will not return all possible {@code long} values.
294 >     *
295 >     * @return the next pseudorandom, uniformly distributed {@code long}
296 >     *         value from this random number generator's sequence
297       */
298      public long nextLong() {
299          // it's okay that the bottom word remains signed.
# Line 293 | Line 302 | class Random implements java.io.Serializ
302  
303      /**
304       * Returns the next pseudorandom, uniformly distributed
305 <     * <code>boolean</code> value from this random number generator's
306 <     * sequence. The general contract of <tt>nextBoolean</tt> is that one
307 <     * <tt>boolean</tt> value is pseudorandomly generated and returned.  The
308 <     * values <code>true</code> and <code>false</code> are produced with
309 <     * (approximately) equal probability. The method <tt>nextBoolean</tt> is
310 <     * implemented by class <tt>Random</tt> as follows:
311 <     * <blockquote><pre>
312 <     * public boolean nextBoolean() {return next(1) != 0;}
313 <     * </pre></blockquote>
314 <     * @return  the next pseudorandom, uniformly distributed
315 <     *          <code>boolean</code> value from this random number generator's
316 <     *          sequence.
305 >     * {@code boolean} value from this random number generator's
306 >     * sequence. The general contract of {@code nextBoolean} is that one
307 >     * {@code boolean} value is pseudorandomly generated and returned.  The
308 >     * values {@code true} and {@code false} are produced with
309 >     * (approximately) equal probability.
310 >     *
311 >     * <p>The method {@code nextBoolean} is implemented by class {@code Random}
312 >     * as if by:
313 >     *  <pre> {@code
314 >     * public boolean nextBoolean() {
315 >     *   return next(1) != 0;
316 >     * }}</pre>
317 >     *
318 >     * @return the next pseudorandom, uniformly distributed
319 >     *         {@code boolean} value from this random number generator's
320 >     *         sequence
321       * @since 1.2
322       */
323 <    public boolean nextBoolean() {return next(1) != 0;}
323 >    public boolean nextBoolean() {
324 >        return next(1) != 0;
325 >    }
326  
327      /**
328 <     * Returns the next pseudorandom, uniformly distributed <code>float</code>
329 <     * value between <code>0.0</code> and <code>1.0</code> from this random
330 <     * number generator's sequence. <p>
331 <     * The general contract of <tt>nextFloat</tt> is that one <tt>float</tt>
332 <     * value, chosen (approximately) uniformly from the range <tt>0.0f</tt>
333 <     * (inclusive) to <tt>1.0f</tt> (exclusive), is pseudorandomly
334 <     * generated and returned. All 2<font size="-1"><sup>24</sup></font>
335 <     * possible <tt>float</tt> values of the form
336 <     * <i>m&nbsp;x&nbsp</i>2<font size="-1"><sup>-24</sup></font>, where
337 <     * <i>m</i> is a positive integer less than 2<font size="-1"><sup>24</sup>
338 <     * </font>, are produced with (approximately) equal probability. The
339 <     * method <tt>nextFloat</tt> is implemented by class <tt>Random</tt> as
340 <     * follows:
341 <     * <blockquote><pre>
328 >     * Returns the next pseudorandom, uniformly distributed {@code float}
329 >     * value between {@code 0.0} and {@code 1.0} from this random
330 >     * number generator's sequence.
331 >     *
332 >     * <p>The general contract of {@code nextFloat} is that one
333 >     * {@code float} value, chosen (approximately) uniformly from the
334 >     * range {@code 0.0f} (inclusive) to {@code 1.0f} (exclusive), is
335 >     * pseudorandomly generated and returned. All 2<font
336 >     * size="-1"><sup>24</sup></font> possible {@code float} values
337 >     * of the form <i>m&nbsp;x&nbsp</i>2<font
338 >     * size="-1"><sup>-24</sup></font>, where <i>m</i> is a positive
339 >     * integer less than 2<font size="-1"><sup>24</sup> </font>, are
340 >     * produced with (approximately) equal probability.
341 >     *
342 >     * <p>The method {@code nextFloat} is implemented by class {@code Random}
343 >     * as if by:
344 >     *  <pre> {@code
345       * public float nextFloat() {
346 <     *      return next(24) / ((float)(1 << 24));
347 <     * }</pre></blockquote>
348 <     * The hedge "approximately" is used in the foregoing description only
349 <     * because the next method is only approximately an unbiased source of
350 <     * independently chosen bits. If it were a perfect source or randomly
351 <     * chosen bits, then the algorithm shown would choose <tt>float</tt>
346 >     *   return next(24) / ((float)(1 << 24));
347 >     * }}</pre>
348 >     *
349 >     * <p>The hedge "approximately" is used in the foregoing description only
350 >     * because the next method is only approximately an unbiased source of
351 >     * independently chosen bits. If it were a perfect source of randomly
352 >     * chosen bits, then the algorithm shown would choose {@code float}
353       * values from the stated range with perfect uniformity.<p>
354       * [In early versions of Java, the result was incorrectly calculated as:
355 <     * <blockquote><pre>
356 <     * return next(30) / ((float)(1 << 30));</pre></blockquote>
357 <     * This might seem to be equivalent, if not better, but in fact it
358 <     * introduced a slight nonuniformity because of the bias in the rounding
359 <     * of floating-point numbers: it was slightly more likely that the
360 <     * low-order bit of the significand would be 0 than that it would be 1.]
361 <     *
362 <     * @return  the next pseudorandom, uniformly distributed <code>float</code>
363 <     *          value between <code>0.0</code> and <code>1.0</code> from this
364 <     *          random number generator's sequence.
355 >     *  <pre> {@code
356 >     *   return next(30) / ((float)(1 << 30));}</pre>
357 >     * This might seem to be equivalent, if not better, but in fact it
358 >     * introduced a slight nonuniformity because of the bias in the rounding
359 >     * of floating-point numbers: it was slightly more likely that the
360 >     * low-order bit of the significand would be 0 than that it would be 1.]
361 >     *
362 >     * @return the next pseudorandom, uniformly distributed {@code float}
363 >     *         value between {@code 0.0} and {@code 1.0} from this
364 >     *         random number generator's sequence
365       */
366      public float nextFloat() {
367 <        int i = next(24);
349 <        return i / ((float)(1 << 24));
367 >        return next(24) / ((float)(1 << 24));
368      }
369  
370      /**
371 <     * Returns the next pseudorandom, uniformly distributed
372 <     * <code>double</code> value between <code>0.0</code> and
373 <     * <code>1.0</code> from this random number generator's sequence. <p>
374 <     * The general contract of <tt>nextDouble</tt> is that one
375 <     * <tt>double</tt> value, chosen (approximately) uniformly from the
376 <     * range <tt>0.0d</tt> (inclusive) to <tt>1.0d</tt> (exclusive), is
377 <     * pseudorandomly generated and returned. All
378 <     * 2<font size="-1"><sup>53</sup></font> possible <tt>float</tt>
379 <     * values of the form <i>m&nbsp;x&nbsp;</i>2<font size="-1"><sup>-53</sup>
380 <     * </font>, where <i>m</i> is a positive integer less than
381 <     * 2<font size="-1"><sup>53</sup></font>, are produced with
382 <     * (approximately) equal probability. The method <tt>nextDouble</tt> is
365 <     * implemented by class <tt>Random</tt> as follows:
366 <     * <blockquote><pre>
371 >     * Returns the next pseudorandom, uniformly distributed
372 >     * {@code double} value between {@code 0.0} and
373 >     * {@code 1.0} from this random number generator's sequence.
374 >     *
375 >     * <p>The general contract of {@code nextDouble} is that one
376 >     * {@code double} value, chosen (approximately) uniformly from the
377 >     * range {@code 0.0d} (inclusive) to {@code 1.0d} (exclusive), is
378 >     * pseudorandomly generated and returned.
379 >     *
380 >     * <p>The method {@code nextDouble} is implemented by class {@code Random}
381 >     * as if by:
382 >     *  <pre> {@code
383       * public double nextDouble() {
384 <     *       return (((long)next(26) << 27) + next(27))
385 <     *           / (double)(1L << 53);
386 <     * }</pre></blockquote><p>
387 <     * The hedge "approximately" is used in the foregoing description only
388 <     * because the <tt>next</tt> method is only approximately an unbiased
389 <     * source of independently chosen bits. If it were a perfect source or
390 <     * randomly chosen bits, then the algorithm shown would choose
391 <     * <tt>double</tt> values from the stated range with perfect uniformity.
384 >     *   return (((long)next(26) << 27) + next(27))
385 >     *     / (double)(1L << 53);
386 >     * }}</pre>
387 >     *
388 >     * <p>The hedge "approximately" is used in the foregoing description only
389 >     * because the {@code next} method is only approximately an unbiased
390 >     * source of independently chosen bits. If it were a perfect source of
391 >     * randomly chosen bits, then the algorithm shown would choose
392 >     * {@code double} values from the stated range with perfect uniformity.
393       * <p>[In early versions of Java, the result was incorrectly calculated as:
394 <     * <blockquote><pre>
395 <     *  return (((long)next(27) << 27) + next(27))
396 <     *      / (double)(1L << 54);</pre></blockquote>
397 <     * This might seem to be equivalent, if not better, but in fact it
398 <     * introduced a large nonuniformity because of the bias in the rounding
399 <     * of floating-point numbers: it was three times as likely that the
400 <     * low-order bit of the significand would be 0 than that it would be
401 <     * 1! This nonuniformity probably doesn't matter much in practice, but
402 <     * we strive for perfection.]
403 <     *
404 <     * @return  the next pseudorandom, uniformly distributed
405 <     *          <code>double</code> value between <code>0.0</code> and
406 <     *          <code>1.0</code> from this random number generator's sequence.
394 >     *  <pre> {@code
395 >     *   return (((long)next(27) << 27) + next(27))
396 >     *     / (double)(1L << 54);}</pre>
397 >     * This might seem to be equivalent, if not better, but in fact it
398 >     * introduced a large nonuniformity because of the bias in the rounding
399 >     * of floating-point numbers: it was three times as likely that the
400 >     * low-order bit of the significand would be 0 than that it would be 1!
401 >     * This nonuniformity probably doesn't matter much in practice, but we
402 >     * strive for perfection.]
403 >     *
404 >     * @return the next pseudorandom, uniformly distributed {@code double}
405 >     *         value between {@code 0.0} and {@code 1.0} from this
406 >     *         random number generator's sequence
407 >     * @see Math#random
408       */
409      public double nextDouble() {
410 <        long l = ((long)(next(26)) << 27) + next(27);
411 <        return l / (double)(1L << 53);
410 >        return (((long)(next(26)) << 27) + next(27))
411 >            / (double)(1L << 53);
412      }
413  
414      private double nextNextGaussian;
# Line 398 | Line 416 | class Random implements java.io.Serializ
416  
417      /**
418       * Returns the next pseudorandom, Gaussian ("normally") distributed
419 <     * <code>double</code> value with mean <code>0.0</code> and standard
420 <     * deviation <code>1.0</code> from this random number generator's sequence.
419 >     * {@code double} value with mean {@code 0.0} and standard
420 >     * deviation {@code 1.0} from this random number generator's sequence.
421       * <p>
422 <     * The general contract of <tt>nextGaussian</tt> is that one
423 <     * <tt>double</tt> value, chosen from (approximately) the usual
424 <     * normal distribution with mean <tt>0.0</tt> and standard deviation
425 <     * <tt>1.0</tt>, is pseudorandomly generated and returned. The method
426 <     * <tt>nextGaussian</tt> is implemented by class <tt>Random</tt> as follows:
427 <     * <blockquote><pre>
428 <     * synchronized public double nextGaussian() {
429 <     *    if (haveNextNextGaussian) {
430 <     *            haveNextNextGaussian = false;
431 <     *            return nextNextGaussian;
432 <     *    } else {
433 <     *            double v1, v2, s;
434 <     *            do {
435 <     *                    v1 = 2 * nextDouble() - 1;   // between -1.0 and 1.0
436 <     *                    v2 = 2 * nextDouble() - 1;   // between -1.0 and 1.0
437 <     *                    s = v1 * v1 + v2 * v2;
438 <     *            } while (s >= 1 || s == 0);
439 <     *            double multiplier = Math.sqrt(-2 * Math.log(s)/s);
440 <     *            nextNextGaussian = v2 * multiplier;
441 <     *            haveNextNextGaussian = true;
442 <     *            return v1 * multiplier;
443 <     *    }
444 <     * }</pre></blockquote>
445 <     * This uses the <i>polar method</i> of G. E. P. Box, M. E. Muller, and
446 <     * G. Marsaglia, as described by Donald E. Knuth in <i>The Art of
447 <     * Computer Programming</i>, Volume 2: <i>Seminumerical Algorithms</i>,
422 >     * The general contract of {@code nextGaussian} is that one
423 >     * {@code double} value, chosen from (approximately) the usual
424 >     * normal distribution with mean {@code 0.0} and standard deviation
425 >     * {@code 1.0}, is pseudorandomly generated and returned.
426 >     *
427 >     * <p>The method {@code nextGaussian} is implemented by class
428 >     * {@code Random} as if by a threadsafe version of the following:
429 >     *  <pre> {@code
430 >     * private double nextNextGaussian;
431 >     * private boolean haveNextNextGaussian = false;
432 >     *
433 >     * public double nextGaussian() {
434 >     *   if (haveNextNextGaussian) {
435 >     *     haveNextNextGaussian = false;
436 >     *     return nextNextGaussian;
437 >     *   } else {
438 >     *     double v1, v2, s;
439 >     *     do {
440 >     *       v1 = 2 * nextDouble() - 1;   // between -1.0 and 1.0
441 >     *       v2 = 2 * nextDouble() - 1;   // between -1.0 and 1.0
442 >     *       s = v1 * v1 + v2 * v2;
443 >     *     } while (s >= 1 || s == 0);
444 >     *     double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s);
445 >     *     nextNextGaussian = v2 * multiplier;
446 >     *     haveNextNextGaussian = true;
447 >     *     return v1 * multiplier;
448 >     *   }
449 >     * }}</pre>
450 >     * This uses the <i>polar method</i> of G. E. P. Box, M. E. Muller, and
451 >     * G. Marsaglia, as described by Donald E. Knuth in <i>The Art of
452 >     * Computer Programming</i>, Volume 3: <i>Seminumerical Algorithms</i>,
453       * section 3.4.1, subsection C, algorithm P. Note that it generates two
454 <     * independent values at the cost of only one call to <tt>Math.log</tt>
455 <     * and one call to <tt>Math.sqrt</tt>.
454 >     * independent values at the cost of only one call to {@code StrictMath.log}
455 >     * and one call to {@code StrictMath.sqrt}.
456       *
457 <     * @return  the next pseudorandom, Gaussian ("normally") distributed
458 <     *          <code>double</code> value with mean <code>0.0</code> and
459 <     *          standard deviation <code>1.0</code> from this random number
460 <     *          generator's sequence.
457 >     * @return the next pseudorandom, Gaussian ("normally") distributed
458 >     *         {@code double} value with mean {@code 0.0} and
459 >     *         standard deviation {@code 1.0} from this random number
460 >     *         generator's sequence
461       */
462      synchronized public double nextGaussian() {
463          // See Knuth, ACP, Section 3.4.1 Algorithm C.
464          if (haveNextNextGaussian) {
465 <            haveNextNextGaussian = false;
466 <            return nextNextGaussian;
467 <        } else {
465 >            haveNextNextGaussian = false;
466 >            return nextNextGaussian;
467 >        } else {
468              double v1, v2, s;
469 <            do {
469 >            do {
470                  v1 = 2 * nextDouble() - 1; // between -1 and 1
471 <                v2 = 2 * nextDouble() - 1; // between -1 and 1
471 >                v2 = 2 * nextDouble() - 1; // between -1 and 1
472                  s = v1 * v1 + v2 * v2;
473 <            } while (s >= 1 || s == 0);
474 <            double multiplier = Math.sqrt(-2 * Math.log(s)/s);
475 <            nextNextGaussian = v2 * multiplier;
476 <            haveNextNextGaussian = true;
477 <            return v1 * multiplier;
473 >            } while (s >= 1 || s == 0);
474 >            double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s);
475 >            nextNextGaussian = v2 * multiplier;
476 >            haveNextNextGaussian = true;
477 >            return v1 * multiplier;
478          }
479      }
480  
481      /**
482       * Serializable fields for Random.
483       *
484 <     * @serialField    seed long;
484 >     * @serialField    seed long
485       *              seed for random computations
486 <     * @serialField    nextNextGaussian double;
486 >     * @serialField    nextNextGaussian double
487       *              next Gaussian to be returned
488       * @serialField      haveNextNextGaussian boolean
489       *              nextNextGaussian is valid
# Line 469 | Line 492 | class Random implements java.io.Serializ
492          new ObjectStreamField("seed", Long.TYPE),
493          new ObjectStreamField("nextNextGaussian", Double.TYPE),
494          new ObjectStreamField("haveNextNextGaussian", Boolean.TYPE)
495 <        };
495 >    };
496  
497      /**
498 <     * Reconstitute the <tt>Random</tt> instance from a stream (that is,
499 <     * deserialize it). The seed is read in as long for
477 <     * historical reasons, but it is converted to an AtomicLong.
498 >     * Reconstitute the {@code Random} instance from a stream (that is,
499 >     * deserialize it).
500       */
501      private void readObject(java.io.ObjectInputStream s)
502          throws java.io.IOException, ClassNotFoundException {
503  
504          ObjectInputStream.GetField fields = s.readFields();
483        long seedVal;
505  
506 <        seedVal = (long) fields.get("seed", -1L);
506 >        // The seed is read in as {@code long} for
507 >        // historical reasons, but it is converted to an AtomicLong.
508 >        long seedVal = (long) fields.get("seed", -1L);
509          if (seedVal < 0)
510            throw new java.io.StreamCorruptedException(
511                                "Random: invalid seed");
512 <        seed = seedVal;
512 >        resetSeed(seedVal);
513          nextNextGaussian = fields.get("nextNextGaussian", 0.0);
514          haveNextNextGaussian = fields.get("haveNextNextGaussian", false);
515      }
516  
494
517      /**
518 <     * Save the <tt>Random</tt> instance to a stream.
497 <     * The seed of a Random is serialized as a long for
498 <     * historical reasons.
499 <     *
518 >     * Save the {@code Random} instance to a stream.
519       */
520 <    synchronized private void writeObject(ObjectOutputStream s) throws IOException {
520 >    synchronized private void writeObject(ObjectOutputStream s)
521 >        throws IOException {
522 >
523          // set the values of the Serializable fields
524          ObjectOutputStream.PutField fields = s.putFields();
525 <        fields.put("seed", seed);
525 >
526 >        // The seed is serialized as a long for historical reasons.
527 >        fields.put("seed", seed.get());
528          fields.put("nextNextGaussian", nextNextGaussian);
529          fields.put("haveNextNextGaussian", haveNextNextGaussian);
530  
531          // save them
532          s.writeFields();
510
533      }
534  
535 < }    
535 >    // Support for resetting seed while deserializing
536 >    private static final Unsafe unsafe = Unsafe.getUnsafe();
537 >    private static final long seedOffset;
538 >    static {
539 >        try {
540 >            seedOffset = unsafe.objectFieldOffset
541 >                (Random.class.getDeclaredField("seed"));
542 >        } catch (Exception ex) { throw new Error(ex); }
543 >    }
544 >    private void resetSeed(long seedVal) {
545 >        unsafe.putObjectVolatile(this, seedOffset, new AtomicLong(seedVal));
546 >    }
547 > }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines