ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/SplittableRandom.java
Revision: 1.21
Committed: Thu Sep 19 23:19:43 2013 UTC (10 years, 7 months ago) by dl
Branch: MAIN
Changes since 1.20: +93 -69 lines
Log Message:
minor improvements

File Contents

# User Rev Content
1 dl 1.1 /*
2     * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
3     * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4     *
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    
28 dl 1.18 import java.security.SecureRandom;
29 dl 1.21 import java.net.NetworkInterface;
30     import java.util.Enumeration;
31 dl 1.1 import java.util.concurrent.atomic.AtomicLong;
32     import java.util.function.IntConsumer;
33     import java.util.function.LongConsumer;
34     import java.util.function.DoubleConsumer;
35     import java.util.stream.StreamSupport;
36     import java.util.stream.IntStream;
37     import java.util.stream.LongStream;
38     import java.util.stream.DoubleStream;
39    
40     /**
41     * A generator of uniform pseudorandom values applicable for use in
42     * (among other contexts) isolated parallel computations that may
43 dl 1.18 * generate subtasks. Class {@code SplittableRandom} supports methods for
44 jsr166 1.3 * producing pseudorandom numbers of type {@code int}, {@code long},
45 dl 1.1 * and {@code double} with similar usages as for class
46 jsr166 1.9 * {@link java.util.Random} but differs in the following ways:
47     *
48     * <ul>
49 dl 1.1 *
50     * <li>Series of generated values pass the DieHarder suite testing
51     * independence and uniformity properties of random number generators.
52     * (Most recently validated with <a
53     * href="http://www.phy.duke.edu/~rgb/General/dieharder.php"> version
54     * 3.31.1</a>.) These tests validate only the methods for certain
55     * types and ranges, but similar properties are expected to hold, at
56 dl 1.11 * least approximately, for others as well. The <em>period</em>
57     * (length of any series of generated values before it repeats) is at
58     * least 2<sup>64</sup>. </li>
59 dl 1.1 *
60     * <li> Method {@link #split} constructs and returns a new
61     * SplittableRandom instance that shares no mutable state with the
62 dl 1.7 * current instance. However, with very high probability, the
63     * values collectively generated by the two objects have the same
64 dl 1.1 * statistical properties as if the same quantity of values were
65     * generated by a single thread using a single {@code
66     * SplittableRandom} object. </li>
67     *
68     * <li>Instances of SplittableRandom are <em>not</em> thread-safe.
69     * They are designed to be split, not shared, across threads. For
70     * example, a {@link java.util.concurrent.ForkJoinTask
71     * fork/join-style} computation using random numbers might include a
72     * construction of the form {@code new
73     * Subtask(aSplittableRandom.split()).fork()}.
74     *
75     * <li>This class provides additional methods for generating random
76     * streams, that employ the above techniques when used in {@code
77     * stream.parallel()} mode.</li>
78     *
79     * </ul>
80     *
81 dl 1.18 * <p>Instances of {@code SplittableRandom} are not cryptographically
82     * secure. Consider instead using {@link java.security.SecureRandom}
83     * in security-sensitive applications. Additionally,
84     * default-constructed instances do not use a cryptographically random
85     * seed unless the {@linkplain System#getProperty system property}
86     * {@code java.util.secureRandomSeed} is set to {@code true}.
87     *
88 dl 1.1 * @author Guy Steele
89 dl 1.2 * @author Doug Lea
90 dl 1.1 * @since 1.8
91     */
92     public class SplittableRandom {
93    
94     /*
95     * Implementation Overview.
96     *
97     * This algorithm was inspired by the "DotMix" algorithm by
98     * Leiserson, Schardl, and Sukha "Deterministic Parallel
99     * Random-Number Generation for Dynamic-Multithreading Platforms",
100 dl 1.15 * PPoPP 2012, as well as those in "Parallel random numbers: as
101     * easy as 1, 2, 3" by Salmon, Morae, Dror, and Shaw, SC 2011. It
102     * differs mainly in simplifying and cheapening operations.
103     *
104     * The primary update step (method nextSeed()) is to add a
105     * constant ("gamma") to the current (64 bit) seed, forming a
106     * simple sequence. The seed and the gamma values for any two
107     * SplittableRandom instances are highly likely to be different.
108     *
109     * Methods nextLong, nextInt, and derivatives do not return the
110     * sequence (seed) values, but instead a hash-like bit-mix of
111     * their bits, producing more independently distributed sequences.
112 dl 1.21 * For nextLong, the mix64 function is based on David Stafford's
113     * (http://zimbry.blogspot.com/2011/09/better-bit-mixing-improving-on.html)
114     * "Mix13" variant of the "64-bit finalizer" function in Austin
115     * Appleby's MurmurHash3 algorithm See
116     * http://code.google.com/p/smhasher/wiki/MurmurHash3 . The mix32
117     * function is based on Stafford's Mix04 mix function, but returns
118     * the upper 32 bits cast as int.
119 dl 1.15 *
120     * The split operation uses the current generator to form the seed
121     * and gamma for another SplittableRandom. To conservatively
122     * avoid potential correlations between seed and value generation,
123 dl 1.21 * gamma selection (method mixGamma) uses different
124     * (Murmurhash3's) mix constants. To avoid potential weaknesses
125     * in bit-mixing transformations, we restrict gammas to odd values
126     * with at least 24 0-1 or 1-0 bit transitions. Rather than
127     * rejecting candidates with too few or too many bits set, method
128     * mixGamma flips some bits (which has the effect of mapping at
129     * most 4 to any given gamma value). This reduces the effective
130     * set of 64bit odd gamma values by about 2%, and serves as an
131 dl 1.15 * automated screening for sequence constant selection that is
132     * left as an empirical decision in some other hashing and crypto
133     * algorithms.
134     *
135     * The resulting generator thus transforms a sequence in which
136     * (typically) many bits change on each step, with an inexpensive
137     * mixer with good (but less than cryptographically secure)
138     * avalanching.
139     *
140     * The default (no-argument) constructor, in essence, invokes
141 dl 1.21 * split() for a common "defaultGen" SplittableRandom. Unlike
142     * other cases, this split must be performed in a thread-safe
143     * manner, so we use an AtomicLong to represent the seed rather
144     * than use an explicit SplittableRandom. To bootstrap the
145     * defaultGen, we start off using a seed based on current time and
146     * network interface address unless the java.util.secureRandomSeed
147     * property is set. This serves as a slimmed-down (and insecure)
148     * variant of SecureRandom that also avoids stalls that may occur
149     * when using /dev/random.
150 dl 1.15 *
151     * It is a relatively simple matter to apply the basic design here
152     * to use 128 bit seeds. However, emulating 128bit arithmetic and
153     * carrying around twice the state add more overhead than appears
154     * warranted for current usages.
155 dl 1.13 *
156 dl 1.15 * File organization: First the non-public methods that constitute
157     * the main algorithm, then the main public methods, followed by
158     * some custom spliterator classes needed for stream methods.
159 dl 1.1 */
160    
161     /**
162 dl 1.21 * The golden ratio scaled to 64bits, used as the initial gamma
163     * value for (unsplit) SplittableRandoms.
164 dl 1.1 */
165 dl 1.21 private static final long GOLDEN_GAMMA = 0x9e3779b97f4a7c15L;
166 dl 1.11
167     /**
168 dl 1.5 * The least non-zero value returned by nextDouble(). This value
169 dl 1.7 * is scaled by a random value of 53 bits to produce a result.
170 dl 1.5 */
171 dl 1.21 private static final double DOUBLE_ULP = 1.0 / (1L << 53);
172 dl 1.5
173     /**
174 dl 1.15 * The seed. Updated only via method nextSeed.
175 dl 1.1 */
176     private long seed;
177    
178     /**
179 dl 1.15 * The step value.
180 dl 1.1 */
181     private final long gamma;
182    
183     /**
184 dl 1.15 * Internal constructor used by all others except default constructor.
185 dl 1.1 */
186 dl 1.15 private SplittableRandom(long seed, long gamma) {
187     this.seed = seed;
188     this.gamma = gamma;
189 dl 1.1 }
190    
191     /**
192 dl 1.21 * Computes Stafford variant 13 of 64bit mix function.
193 dl 1.1 */
194     private static long mix64(long z) {
195 dl 1.21 z *= 0xbf58476d1ce4e5b9L;
196     z = (z ^ (z >>> 32)) * 0x94d049bb133111ebL;
197     return z ^ (z >>> 32);
198     }
199    
200     private static long xmix64(long z) {
201     z *= 0xbf58476d1ce4e5b9L;
202     z = (z ^ (z >>> 27)) * 0x94d049bb133111ebL;
203     return z ^ (z >>> 31);
204 dl 1.1 }
205    
206     /**
207 dl 1.21 * Returns the 32 high bits of Stafford variant 4 mix64 function as int.
208 dl 1.1 */
209     private static int mix32(long z) {
210 dl 1.21 z *= 0x62a9d9ed799705f5L;
211     return (int)(((z ^ (z >>> 28)) * 0xcb24d0a5c88c35b3L) >>> 32);
212 dl 1.1 }
213    
214     /**
215 dl 1.15 * Returns the gamma value to use for a new split instance.
216 dl 1.13 */
217 dl 1.21 private static long mixGamma(long z) {
218     z *= 0xff51afd7ed558ccdL; // MurmurHash3 mix constants
219     z = (z ^ (z >>> 33)) * 0xc4ceb9fe1a85ec53L;
220     z = (z ^ (z >>> 33)) | 1L; // force to be odd
221     int n = Long.bitCount(z ^ (z >>> 1)); // ensure enough transitions
222     return (n < 24) ? z ^ 0xaaaaaaaaaaaaaaaaL : z;
223 dl 1.13 }
224    
225     /**
226 dl 1.15 * Adds gamma to seed.
227 dl 1.7 */
228 dl 1.15 private long nextSeed() {
229     return seed += gamma;
230 dl 1.7 }
231    
232     /**
233 dl 1.15 * The seed generator for default constructors.
234 dl 1.7 */
235 dl 1.21 private static final AtomicLong defaultGen = new AtomicLong(initialSeed());
236 dl 1.7
237 dl 1.18 private static long initialSeed() {
238 dl 1.21 String pp = java.security.AccessController.doPrivileged(
239     new sun.security.action.GetPropertyAction(
240     "java.util.secureRandomSeed"));
241     if (pp != null && pp.equalsIgnoreCase("true")) {
242     byte[] seedBytes = java.security.SecureRandom.getSeed(8);
243     long s = (long)(seedBytes[0]) & 0xffL;
244     for (int i = 1; i < 8; ++i)
245     s = (s << 8) | ((long)(seedBytes[i]) & 0xffL);
246     return s;
247 dl 1.18 }
248 dl 1.21 long h = 0L;
249 jsr166 1.17 try {
250 dl 1.21 Enumeration<NetworkInterface> ifcs =
251     NetworkInterface.getNetworkInterfaces();
252     boolean retry = false; // retry once if getHardwareAddress is null
253     while (ifcs.hasMoreElements()) {
254     NetworkInterface ifc = ifcs.nextElement();
255     if (!ifc.isVirtual()) { // skip fake addresses
256     byte[] bs = ifc.getHardwareAddress();
257     if (bs != null) {
258     int n = bs.length;
259     int m = Math.min(n >>> 1, 4);
260     for (int i = 0; i < m; ++i)
261     h = (h << 16) ^ (bs[i] << 8) ^ bs[n-1-i];
262     if (m < 4)
263     h = (h << 8) ^ bs[n-1-m];
264     h = mix64(h);
265     break;
266     }
267     else if (!retry)
268     retry = true;
269     else
270     break;
271     }
272     }
273 dl 1.18 } catch (Exception ignore) {
274 jsr166 1.17 }
275 dl 1.21 return (h ^ mix64(System.currentTimeMillis()) ^
276 dl 1.18 mix64(System.nanoTime()));
277 dl 1.1 }
278    
279 dl 1.15 // IllegalArgumentException messages
280     static final String BadBound = "bound must be positive";
281     static final String BadRange = "bound must be greater than origin";
282     static final String BadSize = "size must be non-negative";
283 dl 1.12
284 dl 1.1 /*
285     * Internal versions of nextX methods used by streams, as well as
286     * the public nextX(origin, bound) methods. These exist mainly to
287     * avoid the need for multiple versions of stream spliterators
288     * across the different exported forms of streams.
289     */
290    
291     /**
292     * The form of nextLong used by LongStream Spliterators. If
293     * origin is greater than bound, acts as unbounded form of
294     * nextLong, else as bounded form.
295     *
296     * @param origin the least value, unless greater than bound
297     * @param bound the upper bound (exclusive), must not equal origin
298     * @return a pseudorandom value
299     */
300     final long internalNextLong(long origin, long bound) {
301     /*
302     * Four Cases:
303     *
304     * 1. If the arguments indicate unbounded form, act as
305     * nextLong().
306     *
307     * 2. If the range is an exact power of two, apply the
308     * associated bit mask.
309     *
310     * 3. If the range is positive, loop to avoid potential bias
311     * when the implicit nextLong() bound (2<sup>64</sup>) is not
312     * evenly divisible by the range. The loop rejects candidates
313     * computed from otherwise over-represented values. The
314     * expected number of iterations under an ideal generator
315 dl 1.4 * varies from 1 to 2, depending on the bound. The loop itself
316     * takes an unlovable form. Because the first candidate is
317     * already available, we need a break-in-the-middle
318     * construction, which is concisely but cryptically performed
319     * within the while-condition of a body-less for loop.
320 dl 1.1 *
321     * 4. Otherwise, the range cannot be represented as a positive
322 dl 1.4 * long. The loop repeatedly generates unbounded longs until
323     * obtaining a candidate meeting constraints (with an expected
324     * number of iterations of less than two).
325 dl 1.1 */
326    
327     long r = mix64(nextSeed());
328     if (origin < bound) {
329     long n = bound - origin, m = n - 1;
330 dl 1.7 if ((n & m) == 0L) // power of two
331 dl 1.1 r = (r & m) + origin;
332 dl 1.7 else if (n > 0L) { // reject over-represented candidates
333 dl 1.1 for (long u = r >>> 1; // ensure nonnegative
334 dl 1.7 u + m - (r = u % n) < 0L; // rejection check
335 dl 1.1 u = mix64(nextSeed()) >>> 1) // retry
336     ;
337     r += origin;
338     }
339 dl 1.7 else { // range not representable as long
340 dl 1.1 while (r < origin || r >= bound)
341     r = mix64(nextSeed());
342     }
343     }
344     return r;
345     }
346    
347     /**
348     * The form of nextInt used by IntStream Spliterators.
349     * Exactly the same as long version, except for types.
350     *
351     * @param origin the least value, unless greater than bound
352     * @param bound the upper bound (exclusive), must not equal origin
353     * @return a pseudorandom value
354     */
355     final int internalNextInt(int origin, int bound) {
356     int r = mix32(nextSeed());
357     if (origin < bound) {
358     int n = bound - origin, m = n - 1;
359 dl 1.13 if ((n & m) == 0)
360 dl 1.1 r = (r & m) + origin;
361     else if (n > 0) {
362     for (int u = r >>> 1;
363 dl 1.7 u + m - (r = u % n) < 0;
364 dl 1.1 u = mix32(nextSeed()) >>> 1)
365     ;
366     r += origin;
367     }
368     else {
369     while (r < origin || r >= bound)
370     r = mix32(nextSeed());
371     }
372     }
373     return r;
374     }
375    
376     /**
377     * The form of nextDouble used by DoubleStream Spliterators.
378     *
379     * @param origin the least value, unless greater than bound
380     * @param bound the upper bound (exclusive), must not equal origin
381     * @return a pseudorandom value
382     */
383     final double internalNextDouble(double origin, double bound) {
384 dl 1.21 double r = (nextLong() >>> 11) * DOUBLE_ULP;
385 dl 1.1 if (origin < bound) {
386     r = r * (bound - origin) + origin;
387 dl 1.7 if (r >= bound) // correct for rounding
388 dl 1.1 r = Double.longBitsToDouble(Double.doubleToLongBits(bound) - 1);
389     }
390     return r;
391     }
392    
393     /* ---------------- public methods ---------------- */
394    
395     /**
396 dl 1.7 * Creates a new SplittableRandom instance using the specified
397     * initial seed. SplittableRandom instances created with the same
398 dl 1.11 * seed in the same program generate identical sequences of values.
399 dl 1.1 *
400     * @param seed the initial seed
401     */
402     public SplittableRandom(long seed) {
403 dl 1.21 this(seed, GOLDEN_GAMMA);
404 dl 1.1 }
405    
406     /**
407     * Creates a new SplittableRandom instance that is likely to
408     * generate sequences of values that are statistically independent
409     * of those of any other instances in the current program; and
410     * may, and typically does, vary across program invocations.
411     */
412 dl 1.21 public SplittableRandom() { // emulate defaultGen.split()
413     long s = defaultGen.getAndAdd(2*GOLDEN_GAMMA);
414     this.seed = mix64(s);
415     this.gamma = mixGamma(s + GOLDEN_GAMMA);
416 dl 1.1 }
417    
418     /**
419     * Constructs and returns a new SplittableRandom instance that
420     * shares no mutable state with this instance. However, with very
421     * high probability, the set of values collectively generated by
422     * the two objects has the same statistical properties as if the
423     * same quantity of values were generated by a single thread using
424     * a single SplittableRandom object. Either or both of the two
425     * objects may be further split using the {@code split()} method,
426     * and the same expected statistical properties apply to the
427     * entire set of generators constructed by such recursive
428     * splitting.
429     *
430     * @return the new SplittableRandom instance
431     */
432     public SplittableRandom split() {
433 dl 1.21 return new SplittableRandom(nextLong(), mixGamma(nextSeed()));
434 dl 1.1 }
435    
436     /**
437     * Returns a pseudorandom {@code int} value.
438     *
439 dl 1.7 * @return a pseudorandom {@code int} value
440 dl 1.1 */
441     public int nextInt() {
442     return mix32(nextSeed());
443     }
444    
445     /**
446 dl 1.7 * Returns a pseudorandom {@code int} value between zero (inclusive)
447 dl 1.1 * and the specified bound (exclusive).
448     *
449 dl 1.18 * @param bound the upper bound (exclusive). Must be positive.
450 dl 1.7 * @return a pseudorandom {@code int} value between zero
451 jsr166 1.10 * (inclusive) and the bound (exclusive)
452 dl 1.16 * @throws IllegalArgumentException if {@code bound} is not positive
453 dl 1.1 */
454     public int nextInt(int bound) {
455     if (bound <= 0)
456 dl 1.15 throw new IllegalArgumentException(BadBound);
457 dl 1.1 // Specialize internalNextInt for origin 0
458     int r = mix32(nextSeed());
459     int m = bound - 1;
460 dl 1.13 if ((bound & m) == 0) // power of two
461 dl 1.1 r &= m;
462     else { // reject over-represented candidates
463     for (int u = r >>> 1;
464 dl 1.7 u + m - (r = u % bound) < 0;
465 dl 1.1 u = mix32(nextSeed()) >>> 1)
466     ;
467     }
468     return r;
469     }
470    
471     /**
472     * Returns a pseudorandom {@code int} value between the specified
473     * origin (inclusive) and the specified bound (exclusive).
474     *
475     * @param origin the least value returned
476     * @param bound the upper bound (exclusive)
477     * @return a pseudorandom {@code int} value between the origin
478 jsr166 1.10 * (inclusive) and the bound (exclusive)
479 dl 1.7 * @throws IllegalArgumentException if {@code origin} is greater than
480 dl 1.1 * or equal to {@code bound}
481     */
482     public int nextInt(int origin, int bound) {
483     if (origin >= bound)
484 dl 1.15 throw new IllegalArgumentException(BadRange);
485 dl 1.1 return internalNextInt(origin, bound);
486     }
487    
488     /**
489     * Returns a pseudorandom {@code long} value.
490     *
491 dl 1.7 * @return a pseudorandom {@code long} value
492 dl 1.1 */
493     public long nextLong() {
494     return mix64(nextSeed());
495     }
496    
497     /**
498 dl 1.7 * Returns a pseudorandom {@code long} value between zero (inclusive)
499 dl 1.1 * and the specified bound (exclusive).
500     *
501 dl 1.18 * @param bound the upper bound (exclusive). Must be positive.
502 dl 1.7 * @return a pseudorandom {@code long} value between zero
503 jsr166 1.10 * (inclusive) and the bound (exclusive)
504 dl 1.16 * @throws IllegalArgumentException if {@code bound} is not positive
505 dl 1.1 */
506     public long nextLong(long bound) {
507     if (bound <= 0)
508 dl 1.15 throw new IllegalArgumentException(BadBound);
509 dl 1.1 // Specialize internalNextLong for origin 0
510     long r = mix64(nextSeed());
511     long m = bound - 1;
512     if ((bound & m) == 0L) // power of two
513     r &= m;
514     else { // reject over-represented candidates
515     for (long u = r >>> 1;
516     u + m - (r = u % bound) < 0L;
517     u = mix64(nextSeed()) >>> 1)
518     ;
519     }
520     return r;
521     }
522    
523     /**
524     * Returns a pseudorandom {@code long} value between the specified
525     * origin (inclusive) and the specified bound (exclusive).
526     *
527     * @param origin the least value returned
528     * @param bound the upper bound (exclusive)
529     * @return a pseudorandom {@code long} value between the origin
530 jsr166 1.10 * (inclusive) and the bound (exclusive)
531 dl 1.7 * @throws IllegalArgumentException if {@code origin} is greater than
532 dl 1.1 * or equal to {@code bound}
533     */
534     public long nextLong(long origin, long bound) {
535     if (origin >= bound)
536 dl 1.15 throw new IllegalArgumentException(BadRange);
537 dl 1.1 return internalNextLong(origin, bound);
538     }
539    
540     /**
541 dl 1.7 * Returns a pseudorandom {@code double} value between zero
542     * (inclusive) and one (exclusive).
543 dl 1.1 *
544 dl 1.7 * @return a pseudorandom {@code double} value between zero
545 dl 1.18 * (inclusive) and one (exclusive)
546 dl 1.1 */
547     public double nextDouble() {
548 dl 1.21 return (mix64(nextSeed()) >>> 11) * DOUBLE_ULP;
549 dl 1.1 }
550    
551     /**
552     * Returns a pseudorandom {@code double} value between 0.0
553     * (inclusive) and the specified bound (exclusive).
554     *
555 dl 1.18 * @param bound the upper bound (exclusive). Must be positive.
556 dl 1.7 * @return a pseudorandom {@code double} value between zero
557 jsr166 1.10 * (inclusive) and the bound (exclusive)
558 dl 1.16 * @throws IllegalArgumentException if {@code bound} is not positive
559 dl 1.1 */
560     public double nextDouble(double bound) {
561 dl 1.7 if (!(bound > 0.0))
562 dl 1.15 throw new IllegalArgumentException(BadBound);
563 dl 1.21 double result = (mix64(nextSeed()) >>> 11) * DOUBLE_ULP * bound;
564 dl 1.1 return (result < bound) ? result : // correct for rounding
565     Double.longBitsToDouble(Double.doubleToLongBits(bound) - 1);
566     }
567    
568     /**
569 dl 1.7 * Returns a pseudorandom {@code double} value between the specified
570 dl 1.1 * origin (inclusive) and bound (exclusive).
571     *
572     * @param origin the least value returned
573 dl 1.18 * @param bound the upper bound (exclusive)
574 dl 1.1 * @return a pseudorandom {@code double} value between the origin
575 jsr166 1.10 * (inclusive) and the bound (exclusive)
576 dl 1.1 * @throws IllegalArgumentException if {@code origin} is greater than
577     * or equal to {@code bound}
578     */
579     public double nextDouble(double origin, double bound) {
580 dl 1.7 if (!(origin < bound))
581 dl 1.15 throw new IllegalArgumentException(BadRange);
582 dl 1.1 return internalNextDouble(origin, bound);
583     }
584    
585 dl 1.11 /**
586     * Returns a pseudorandom {@code boolean} value.
587     *
588     * @return a pseudorandom {@code boolean} value
589     */
590     public boolean nextBoolean() {
591     return mix32(nextSeed()) < 0;
592     }
593    
594 dl 1.1 // stream methods, coded in a way intended to better isolate for
595     // maintenance purposes the small differences across forms.
596    
597     /**
598 dl 1.16 * Returns a stream producing the given {@code streamSize} number
599     * of pseudorandom {@code int} values from this generator and/or
600     * one split from it.
601 dl 1.1 *
602     * @param streamSize the number of values to generate
603     * @return a stream of pseudorandom {@code int} values
604     * @throws IllegalArgumentException if {@code streamSize} is
605 dl 1.7 * less than zero
606 dl 1.1 */
607     public IntStream ints(long streamSize) {
608     if (streamSize < 0L)
609 dl 1.15 throw new IllegalArgumentException(BadSize);
610 dl 1.1 return StreamSupport.intStream
611     (new RandomIntsSpliterator
612     (this, 0L, streamSize, Integer.MAX_VALUE, 0),
613     false);
614     }
615    
616     /**
617     * Returns an effectively unlimited stream of pseudorandom {@code int}
618 dl 1.16 * values from this generator and/or one split from it.
619 dl 1.1 *
620     * @implNote This method is implemented to be equivalent to {@code
621     * ints(Long.MAX_VALUE)}.
622     *
623     * @return a stream of pseudorandom {@code int} values
624     */
625     public IntStream ints() {
626     return StreamSupport.intStream
627     (new RandomIntsSpliterator
628     (this, 0L, Long.MAX_VALUE, Integer.MAX_VALUE, 0),
629     false);
630     }
631    
632     /**
633 dl 1.16 * Returns a stream producing the given {@code streamSize} number
634 dl 1.18 * of pseudorandom {@code int} values from this generator and/or one split
635     * from it; each value conforms to the given origin (inclusive) and bound
636     * (exclusive).
637 dl 1.1 *
638     * @param streamSize the number of values to generate
639 dl 1.18 * @param randomNumberOrigin the origin (inclusive) of each random value
640     * @param randomNumberBound the bound (exclusive) of each random value
641 dl 1.1 * @return a stream of pseudorandom {@code int} values,
642 dl 1.18 * each with the given origin (inclusive) and bound (exclusive)
643 dl 1.1 * @throws IllegalArgumentException if {@code streamSize} is
644 dl 1.7 * less than zero, or {@code randomNumberOrigin}
645 dl 1.1 * is greater than or equal to {@code randomNumberBound}
646     */
647     public IntStream ints(long streamSize, int randomNumberOrigin,
648     int randomNumberBound) {
649     if (streamSize < 0L)
650 dl 1.15 throw new IllegalArgumentException(BadSize);
651 dl 1.1 if (randomNumberOrigin >= randomNumberBound)
652 dl 1.15 throw new IllegalArgumentException(BadRange);
653 dl 1.1 return StreamSupport.intStream
654     (new RandomIntsSpliterator
655     (this, 0L, streamSize, randomNumberOrigin, randomNumberBound),
656     false);
657     }
658    
659     /**
660     * Returns an effectively unlimited stream of pseudorandom {@code
661 dl 1.18 * int} values from this generator and/or one split from it; each value
662     * conforms to the given origin (inclusive) and bound (exclusive).
663 dl 1.1 *
664     * @implNote This method is implemented to be equivalent to {@code
665     * ints(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
666     *
667 dl 1.18 * @param randomNumberOrigin the origin (inclusive) of each random value
668     * @param randomNumberBound the bound (exclusive) of each random value
669 dl 1.1 * @return a stream of pseudorandom {@code int} values,
670 dl 1.18 * each with the given origin (inclusive) and bound (exclusive)
671 dl 1.1 * @throws IllegalArgumentException if {@code randomNumberOrigin}
672     * is greater than or equal to {@code randomNumberBound}
673     */
674     public IntStream ints(int randomNumberOrigin, int randomNumberBound) {
675     if (randomNumberOrigin >= randomNumberBound)
676 dl 1.15 throw new IllegalArgumentException(BadRange);
677 dl 1.1 return StreamSupport.intStream
678     (new RandomIntsSpliterator
679     (this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
680     false);
681     }
682    
683     /**
684 dl 1.16 * Returns a stream producing the given {@code streamSize} number
685     * of pseudorandom {@code long} values from this generator and/or
686     * one split from it.
687 dl 1.1 *
688     * @param streamSize the number of values to generate
689 dl 1.7 * @return a stream of pseudorandom {@code long} values
690 dl 1.1 * @throws IllegalArgumentException if {@code streamSize} is
691 dl 1.7 * less than zero
692 dl 1.1 */
693     public LongStream longs(long streamSize) {
694     if (streamSize < 0L)
695 dl 1.15 throw new IllegalArgumentException(BadSize);
696 dl 1.1 return StreamSupport.longStream
697     (new RandomLongsSpliterator
698     (this, 0L, streamSize, Long.MAX_VALUE, 0L),
699     false);
700     }
701    
702     /**
703 dl 1.16 * Returns an effectively unlimited stream of pseudorandom {@code
704     * long} values from this generator and/or one split from it.
705 dl 1.1 *
706     * @implNote This method is implemented to be equivalent to {@code
707     * longs(Long.MAX_VALUE)}.
708     *
709     * @return a stream of pseudorandom {@code long} values
710     */
711     public LongStream longs() {
712     return StreamSupport.longStream
713     (new RandomLongsSpliterator
714     (this, 0L, Long.MAX_VALUE, Long.MAX_VALUE, 0L),
715     false);
716     }
717    
718     /**
719 dl 1.7 * Returns a stream producing the given {@code streamSize} number of
720 dl 1.18 * pseudorandom {@code long} values from this generator and/or one split
721     * from it; each value conforms to the given origin (inclusive) and bound
722     * (exclusive).
723 dl 1.1 *
724     * @param streamSize the number of values to generate
725 dl 1.18 * @param randomNumberOrigin the origin (inclusive) of each random value
726     * @param randomNumberBound the bound (exclusive) of each random value
727 dl 1.1 * @return a stream of pseudorandom {@code long} values,
728 dl 1.18 * each with the given origin (inclusive) and bound (exclusive)
729 dl 1.1 * @throws IllegalArgumentException if {@code streamSize} is
730 dl 1.7 * less than zero, or {@code randomNumberOrigin}
731 dl 1.1 * is greater than or equal to {@code randomNumberBound}
732     */
733     public LongStream longs(long streamSize, long randomNumberOrigin,
734     long randomNumberBound) {
735     if (streamSize < 0L)
736 dl 1.15 throw new IllegalArgumentException(BadSize);
737 dl 1.1 if (randomNumberOrigin >= randomNumberBound)
738 dl 1.15 throw new IllegalArgumentException(BadRange);
739 dl 1.1 return StreamSupport.longStream
740     (new RandomLongsSpliterator
741     (this, 0L, streamSize, randomNumberOrigin, randomNumberBound),
742     false);
743     }
744    
745     /**
746     * Returns an effectively unlimited stream of pseudorandom {@code
747 dl 1.18 * long} values from this generator and/or one split from it; each value
748     * conforms to the given origin (inclusive) and bound (exclusive).
749 dl 1.1 *
750     * @implNote This method is implemented to be equivalent to {@code
751     * longs(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
752     *
753 dl 1.18 * @param randomNumberOrigin the origin (inclusive) of each random value
754     * @param randomNumberBound the bound (exclusive) of each random value
755 dl 1.1 * @return a stream of pseudorandom {@code long} values,
756 dl 1.18 * each with the given origin (inclusive) and bound (exclusive)
757 dl 1.1 * @throws IllegalArgumentException if {@code randomNumberOrigin}
758     * is greater than or equal to {@code randomNumberBound}
759     */
760     public LongStream longs(long randomNumberOrigin, long randomNumberBound) {
761     if (randomNumberOrigin >= randomNumberBound)
762 dl 1.15 throw new IllegalArgumentException(BadRange);
763 dl 1.1 return StreamSupport.longStream
764     (new RandomLongsSpliterator
765     (this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
766     false);
767     }
768    
769     /**
770 dl 1.7 * Returns a stream producing the given {@code streamSize} number of
771 dl 1.18 * pseudorandom {@code double} values from this generator and/or one split
772     * from it; each value is between zero (inclusive) and one (exclusive).
773 dl 1.1 *
774     * @param streamSize the number of values to generate
775     * @return a stream of {@code double} values
776     * @throws IllegalArgumentException if {@code streamSize} is
777 dl 1.7 * less than zero
778 dl 1.1 */
779     public DoubleStream doubles(long streamSize) {
780     if (streamSize < 0L)
781 dl 1.15 throw new IllegalArgumentException(BadSize);
782 dl 1.1 return StreamSupport.doubleStream
783     (new RandomDoublesSpliterator
784     (this, 0L, streamSize, Double.MAX_VALUE, 0.0),
785     false);
786     }
787    
788     /**
789     * Returns an effectively unlimited stream of pseudorandom {@code
790 dl 1.18 * double} values from this generator and/or one split from it; each value
791     * is between zero (inclusive) and one (exclusive).
792 dl 1.1 *
793     * @implNote This method is implemented to be equivalent to {@code
794     * doubles(Long.MAX_VALUE)}.
795     *
796     * @return a stream of pseudorandom {@code double} values
797     */
798     public DoubleStream doubles() {
799     return StreamSupport.doubleStream
800     (new RandomDoublesSpliterator
801     (this, 0L, Long.MAX_VALUE, Double.MAX_VALUE, 0.0),
802     false);
803     }
804    
805     /**
806 dl 1.7 * Returns a stream producing the given {@code streamSize} number of
807 dl 1.18 * pseudorandom {@code double} values from this generator and/or one split
808     * from it; each value conforms to the given origin (inclusive) and bound
809     * (exclusive).
810 dl 1.1 *
811     * @param streamSize the number of values to generate
812 dl 1.18 * @param randomNumberOrigin the origin (inclusive) of each random value
813     * @param randomNumberBound the bound (exclusive) of each random value
814 dl 1.1 * @return a stream of pseudorandom {@code double} values,
815 dl 1.18 * each with the given origin (inclusive) and bound (exclusive)
816 dl 1.1 * @throws IllegalArgumentException if {@code streamSize} is
817 dl 1.18 * less than zero
818 dl 1.1 * @throws IllegalArgumentException if {@code randomNumberOrigin}
819     * is greater than or equal to {@code randomNumberBound}
820     */
821     public DoubleStream doubles(long streamSize, double randomNumberOrigin,
822     double randomNumberBound) {
823     if (streamSize < 0L)
824 dl 1.15 throw new IllegalArgumentException(BadSize);
825 dl 1.7 if (!(randomNumberOrigin < randomNumberBound))
826 dl 1.15 throw new IllegalArgumentException(BadRange);
827 dl 1.1 return StreamSupport.doubleStream
828     (new RandomDoublesSpliterator
829     (this, 0L, streamSize, randomNumberOrigin, randomNumberBound),
830     false);
831     }
832    
833     /**
834     * Returns an effectively unlimited stream of pseudorandom {@code
835 dl 1.18 * double} values from this generator and/or one split from it; each value
836     * conforms to the given origin (inclusive) and bound (exclusive).
837 dl 1.1 *
838     * @implNote This method is implemented to be equivalent to {@code
839     * doubles(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
840     *
841 dl 1.18 * @param randomNumberOrigin the origin (inclusive) of each random value
842     * @param randomNumberBound the bound (exclusive) of each random value
843 dl 1.1 * @return a stream of pseudorandom {@code double} values,
844 dl 1.18 * each with the given origin (inclusive) and bound (exclusive)
845 dl 1.1 * @throws IllegalArgumentException if {@code randomNumberOrigin}
846     * is greater than or equal to {@code randomNumberBound}
847     */
848     public DoubleStream doubles(double randomNumberOrigin, double randomNumberBound) {
849 dl 1.7 if (!(randomNumberOrigin < randomNumberBound))
850 dl 1.15 throw new IllegalArgumentException(BadRange);
851 dl 1.1 return StreamSupport.doubleStream
852     (new RandomDoublesSpliterator
853     (this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
854     false);
855     }
856    
857     /**
858     * Spliterator for int streams. We multiplex the four int
859 dl 1.7 * versions into one class by treating a bound less than origin as
860 dl 1.1 * unbounded, and also by treating "infinite" as equivalent to
861     * Long.MAX_VALUE. For splits, it uses the standard divide-by-two
862     * approach. The long and double versions of this class are
863     * identical except for types.
864     */
865 dl 1.11 static final class RandomIntsSpliterator implements Spliterator.OfInt {
866 dl 1.1 final SplittableRandom rng;
867     long index;
868     final long fence;
869     final int origin;
870     final int bound;
871     RandomIntsSpliterator(SplittableRandom rng, long index, long fence,
872     int origin, int bound) {
873     this.rng = rng; this.index = index; this.fence = fence;
874     this.origin = origin; this.bound = bound;
875     }
876    
877     public RandomIntsSpliterator trySplit() {
878     long i = index, m = (i + fence) >>> 1;
879     return (m <= i) ? null :
880     new RandomIntsSpliterator(rng.split(), i, index = m, origin, bound);
881     }
882    
883     public long estimateSize() {
884     return fence - index;
885     }
886    
887     public int characteristics() {
888     return (Spliterator.SIZED | Spliterator.SUBSIZED |
889 dl 1.4 Spliterator.NONNULL | Spliterator.IMMUTABLE);
890 dl 1.1 }
891    
892     public boolean tryAdvance(IntConsumer consumer) {
893     if (consumer == null) throw new NullPointerException();
894     long i = index, f = fence;
895     if (i < f) {
896     consumer.accept(rng.internalNextInt(origin, bound));
897     index = i + 1;
898     return true;
899     }
900     return false;
901     }
902    
903     public void forEachRemaining(IntConsumer consumer) {
904     if (consumer == null) throw new NullPointerException();
905     long i = index, f = fence;
906     if (i < f) {
907     index = f;
908 dl 1.15 SplittableRandom r = rng;
909 dl 1.1 int o = origin, b = bound;
910     do {
911 dl 1.15 consumer.accept(r.internalNextInt(o, b));
912 dl 1.1 } while (++i < f);
913     }
914     }
915     }
916    
917     /**
918     * Spliterator for long streams.
919     */
920 dl 1.11 static final class RandomLongsSpliterator implements Spliterator.OfLong {
921 dl 1.1 final SplittableRandom rng;
922     long index;
923     final long fence;
924     final long origin;
925     final long bound;
926     RandomLongsSpliterator(SplittableRandom rng, long index, long fence,
927     long origin, long bound) {
928     this.rng = rng; this.index = index; this.fence = fence;
929     this.origin = origin; this.bound = bound;
930     }
931    
932     public RandomLongsSpliterator trySplit() {
933     long i = index, m = (i + fence) >>> 1;
934     return (m <= i) ? null :
935     new RandomLongsSpliterator(rng.split(), i, index = m, origin, bound);
936     }
937    
938     public long estimateSize() {
939     return fence - index;
940     }
941    
942     public int characteristics() {
943     return (Spliterator.SIZED | Spliterator.SUBSIZED |
944 dl 1.4 Spliterator.NONNULL | Spliterator.IMMUTABLE);
945 dl 1.1 }
946    
947     public boolean tryAdvance(LongConsumer consumer) {
948     if (consumer == null) throw new NullPointerException();
949     long i = index, f = fence;
950     if (i < f) {
951     consumer.accept(rng.internalNextLong(origin, bound));
952     index = i + 1;
953     return true;
954     }
955     return false;
956     }
957    
958     public void forEachRemaining(LongConsumer consumer) {
959     if (consumer == null) throw new NullPointerException();
960     long i = index, f = fence;
961     if (i < f) {
962     index = f;
963 dl 1.15 SplittableRandom r = rng;
964 dl 1.1 long o = origin, b = bound;
965     do {
966 dl 1.15 consumer.accept(r.internalNextLong(o, b));
967 dl 1.1 } while (++i < f);
968     }
969     }
970    
971     }
972    
973     /**
974     * Spliterator for double streams.
975     */
976 dl 1.11 static final class RandomDoublesSpliterator implements Spliterator.OfDouble {
977 dl 1.1 final SplittableRandom rng;
978     long index;
979     final long fence;
980     final double origin;
981     final double bound;
982     RandomDoublesSpliterator(SplittableRandom rng, long index, long fence,
983     double origin, double bound) {
984     this.rng = rng; this.index = index; this.fence = fence;
985     this.origin = origin; this.bound = bound;
986     }
987    
988     public RandomDoublesSpliterator trySplit() {
989     long i = index, m = (i + fence) >>> 1;
990     return (m <= i) ? null :
991     new RandomDoublesSpliterator(rng.split(), i, index = m, origin, bound);
992     }
993    
994     public long estimateSize() {
995     return fence - index;
996     }
997    
998     public int characteristics() {
999     return (Spliterator.SIZED | Spliterator.SUBSIZED |
1000 dl 1.4 Spliterator.NONNULL | Spliterator.IMMUTABLE);
1001 dl 1.1 }
1002    
1003     public boolean tryAdvance(DoubleConsumer consumer) {
1004     if (consumer == null) throw new NullPointerException();
1005     long i = index, f = fence;
1006     if (i < f) {
1007     consumer.accept(rng.internalNextDouble(origin, bound));
1008     index = i + 1;
1009     return true;
1010     }
1011     return false;
1012     }
1013    
1014     public void forEachRemaining(DoubleConsumer consumer) {
1015     if (consumer == null) throw new NullPointerException();
1016     long i = index, f = fence;
1017     if (i < f) {
1018     index = f;
1019 dl 1.15 SplittableRandom r = rng;
1020 dl 1.1 double o = origin, b = bound;
1021     do {
1022 dl 1.15 consumer.accept(r.internalNextDouble(o, b));
1023 dl 1.1 } while (++i < f);
1024     }
1025     }
1026     }
1027    
1028     }