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.11 by jsr166, Sun Oct 2 07:10:59 2005 UTC vs.
Revision 1.32 by dl, Wed Jan 16 19:01:22 2013 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines