ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/SplittableRandom.java
Revision: 1.4
Committed: Thu Jul 11 13:40:42 2013 UTC (10 years, 9 months ago) by dl
Branch: MAIN
Changes since 1.3: +11 -10 lines
Log Message:
Incorporate suggestions

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     import java.util.concurrent.atomic.AtomicLong;
29     import java.util.Spliterator;
30     import java.util.function.IntConsumer;
31     import java.util.function.LongConsumer;
32     import java.util.function.DoubleConsumer;
33     import java.util.stream.StreamSupport;
34     import java.util.stream.IntStream;
35     import java.util.stream.LongStream;
36     import java.util.stream.DoubleStream;
37    
38    
39     /**
40     * A generator of uniform pseudorandom values applicable for use in
41     * (among other contexts) isolated parallel computations that may
42     * generate subtasks. Class SplittableRandom supports methods for
43 jsr166 1.3 * producing pseudorandom numbers of type {@code int}, {@code long},
44 dl 1.1 * and {@code double} with similar usages as for class
45     * {@link java.util.Random} but differs in the following ways: <ul>
46     *
47     * <li>Series of generated values pass the DieHarder suite testing
48     * independence and uniformity properties of random number generators.
49     * (Most recently validated with <a
50     * href="http://www.phy.duke.edu/~rgb/General/dieharder.php"> version
51     * 3.31.1</a>.) These tests validate only the methods for certain
52     * types and ranges, but similar properties are expected to hold, at
53     * least approximately, for others as well. </li>
54     *
55     * <li> Method {@link #split} constructs and returns a new
56     * SplittableRandom instance that shares no mutable state with the
57     * current instance. However, with very high probability, the set of
58     * values collectively generated by the two objects has the same
59     * statistical properties as if the same quantity of values were
60     * generated by a single thread using a single {@code
61     * SplittableRandom} object. </li>
62     *
63     * <li>Instances of SplittableRandom are <em>not</em> thread-safe.
64     * They are designed to be split, not shared, across threads. For
65     * example, a {@link java.util.concurrent.ForkJoinTask
66     * fork/join-style} computation using random numbers might include a
67     * construction of the form {@code new
68     * Subtask(aSplittableRandom.split()).fork()}.
69     *
70     * <li>This class provides additional methods for generating random
71     * streams, that employ the above techniques when used in {@code
72     * stream.parallel()} mode.</li>
73     *
74     * </ul>
75     *
76     * @author Guy Steele
77 dl 1.2 * @author Doug Lea
78 dl 1.1 * @since 1.8
79     */
80     public class SplittableRandom {
81    
82     /*
83     * File organization: First the non-public methods that constitute
84     * the main algorithm, then the main public methods, followed by
85     * some custom spliterator classes needed for stream methods.
86     *
87     * Credits: Primary algorithm and code by Guy Steele. Stream
88     * support methods by Doug Lea. Documentation jointly produced
89     * with additional help from Brian Goetz.
90     */
91    
92     /*
93     * Implementation Overview.
94     *
95     * This algorithm was inspired by the "DotMix" algorithm by
96     * Leiserson, Schardl, and Sukha "Deterministic Parallel
97     * Random-Number Generation for Dynamic-Multithreading Platforms",
98     * PPoPP 2012, but improves and extends it in several ways.
99     *
100     * The primary update step is simply to add a constant ("gamma")
101     * to the current seed, modulo a prime ("George"). However, the
102     * nextLong and nextInt methods do not return this value, but
103     * instead the results of bit-mixing transformations that produce
104     * more uniformly distributed sequences.
105     *
106     * "George" is the otherwise nameless (because it cannot be
107     * represented) prime number 2^64+13. Using a prime number larger
108     * than can fit in a long ensures that all possible long values
109     * can occur, plus 13 others that just get skipped over when they
110     * are encountered; see method addGammaModGeorge. For this to
111     * work, initial gamma values must be at least 13.
112     *
113     * The value of gamma differs for each instance across a series of
114     * splits, and is generated using a slightly stripped-down variant
115     * of the same algorithm, but operating across calls to split(),
116 dl 1.2 * not calls to nextSeed(): Each instance carries the state of
117 dl 1.1 * this generator as nextSplit, and uses mix64(nextSplit) as its
118     * own gamma value. Computations of gammas themselves use a fixed
119     * constant as the second argument to the addGammaModGeorge
120     * function, GAMMA_GAMMA, a "genuinely random" number from a
121     * radioactive decay reading (obtained from
122     * http://www.fourmilab.ch/hotbits/) meeting the above range
123     * constraint. Using a fixed constant maintains the invariant that
124     * the value of gamma is the same for every instance that is at
125     * the same split-distance from their common root. (Note: there is
126     * nothing especially magic about obtaining this constant from a
127     * "truly random" physical source rather than just choosing one
128     * arbitrarily; using "hotbits" was merely an aesthetically pleasing
129     * choice. In either case, good statistical behavior of the
130     * algorithm should be, and was, verified by using the DieHarder
131     * test suite.)
132     *
133     * The mix64 bit-mixing function called by nextLong and other
134     * methods computes the same value as the "64-bit finalizer"
135     * function in Austin Appleby's MurmurHash3 algorithm. See
136     * http://code.google.com/p/smhasher/wiki/MurmurHash3 , which
137     * comments: "The constants for the finalizers were generated by a
138     * simple simulated-annealing algorithm, and both avalanche all
139     * bits of 'h' to within 0.25% bias." It also appears to work to
140     * use instead any of the variants proposed by David Stafford at
141     * http://zimbry.blogspot.com/2011/09/better-bit-mixing-improving-on.html
142     * but these variants have not yet been tested as thoroughly
143     * in the context of the implementation of SplittableRandom.
144     *
145     * The mix32 function used for nextInt just consists of two of the
146     * five lines of mix64; avalanche testing shows that the 64-bit result
147     * has its top 32 bits avalanched well, though not the bottom 32 bits.
148     * DieHarder tests show that it is adequate for generating one
149     * random int from the 64-bit result of nextSeed.
150     *
151     * Support for the default (no-argument) constructor relies on an
152     * AtomicLong (defaultSeedGenerator) to help perform the
153     * equivalent of a split of a statically constructed
154     * SplittableRandom. Unlike other cases, this split must be
155     * performed in a thread-safe manner. We use
156     * AtomicLong.compareAndSet as the (typically) most efficient
157     * mechanism. To bootstrap, we start off using System.nanotime(),
158     * and update using another "genuinely random" constant
159     * DEFAULT_SEED_GAMMA. The default constructor uses GAMMA_GAMMA,
160     * not 0, for its splitSeed argument (addGammaModGeorge(0,
161     * GAMMA_GAMMA) == GAMMA_GAMMA) to reflect that each is split from
162     * this root generator, even though the root is not explicitly
163     * represented as a SplittableRandom.
164     */
165    
166     /**
167     * The "genuinely random" value for producing new gamma values.
168     * The value is arbitrary, subject to the requirement that it be
169     * greater or equal to 13.
170     */
171     private static final long GAMMA_GAMMA = 0xF2281E2DBA6606F3L;
172    
173     /**
174     * The "genuinely random" seed update value for default constructors.
175     * The value is arbitrary, subject to the requirement that it be
176     * greater or equal to 13.
177     */
178     private static final long DEFAULT_SEED_GAMMA = 0xBD24B73A95FB84D9L;
179    
180     /**
181     * The next seed for default constructors.
182     */
183     private static final AtomicLong defaultSeedGenerator =
184     new AtomicLong(System.nanoTime());
185    
186     /**
187     * The seed, updated only via method nextSeed.
188     */
189     private long seed;
190    
191     /**
192     * The constant value added to seed (mod George) on each update.
193     */
194     private final long gamma;
195    
196     /**
197     * The next seed to use for splits. Propagated using
198     * addGammaModGeorge across instances.
199     */
200     private final long nextSplit;
201    
202     /**
203     * Internal constructor used by all other constructors and by
204     * method split. Establishes the initial seed for this instance,
205     * and uses the given splitSeed to establish gamma, as well as the
206     * nextSplit to use by this instance.
207     */
208     private SplittableRandom(long seed, long splitSeed) {
209     this.seed = seed;
210     long s = splitSeed, g;
211     do { // ensure gamma >= 13, considered as an unsigned integer
212     s = addGammaModGeorge(s, GAMMA_GAMMA);
213     g = mix64(s);
214     } while (Long.compareUnsigned(g, 13L) < 0);
215     this.gamma = g;
216     this.nextSplit = s;
217     }
218    
219     /**
220     * Adds the given gamma value, g, to the given seed value s, mod
221     * George (2^64+13). We regard s and g as unsigned values
222     * (ranging from 0 to 2^64-1). We add g to s either once or twice
223     * (mod George) as necessary to produce an (unsigned) result less
224     * than 2^64. We require that g must be at least 13. This
225     * guarantees that if (s+g) mod George >= 2^64 then (s+g+g) mod
226     * George < 2^64; thus we need only a conditional, not a loop,
227     * to be sure of getting a representable value.
228     *
229     * @param s a seed value
230     * @param g a gamma value, 13 <= g (as unsigned)
231     */
232     private static long addGammaModGeorge(long s, long g) {
233     long p = s + g;
234     if (Long.compareUnsigned(p, g) >= 0)
235     return p;
236     long q = p - 13L;
237     return (Long.compareUnsigned(p, 13L) >= 0) ? q : (q + g);
238     }
239    
240     /**
241     * Updates in-place and returns seed.
242     * See above for explanation.
243     */
244     private long nextSeed() {
245     return seed = addGammaModGeorge(seed, gamma);
246     }
247    
248     /**
249     * Returns a bit-mixed transformation of its argument.
250     * See above for explanation.
251     */
252     private static long mix64(long z) {
253     z ^= (z >>> 33);
254     z *= 0xff51afd7ed558ccdL;
255     z ^= (z >>> 33);
256     z *= 0xc4ceb9fe1a85ec53L;
257     z ^= (z >>> 33);
258     return z;
259     }
260    
261     /**
262     * Returns a bit-mixed int transformation of its argument.
263     * See above for explanation.
264     */
265     private static int mix32(long z) {
266     z ^= (z >>> 33);
267     z *= 0xc4ceb9fe1a85ec53L;
268     return (int)(z >>> 32);
269     }
270    
271     /**
272     * Atomically updates and returns next seed for default constructor
273     */
274     private static long nextDefaultSeed() {
275     long oldSeed, newSeed;
276     do {
277     oldSeed = defaultSeedGenerator.get();
278     newSeed = addGammaModGeorge(oldSeed, DEFAULT_SEED_GAMMA);
279     } while (!defaultSeedGenerator.compareAndSet(oldSeed, newSeed));
280     return mix64(newSeed);
281     }
282    
283     /*
284     * Internal versions of nextX methods used by streams, as well as
285     * the public nextX(origin, bound) methods. These exist mainly to
286     * avoid the need for multiple versions of stream spliterators
287     * across the different exported forms of streams.
288     */
289    
290     /**
291     * The form of nextLong used by LongStream Spliterators. If
292     * origin is greater than bound, acts as unbounded form of
293     * nextLong, else as bounded form.
294     *
295     * @param origin the least value, unless greater than bound
296     * @param bound the upper bound (exclusive), must not equal origin
297     * @return a pseudorandom value
298     */
299     final long internalNextLong(long origin, long bound) {
300     /*
301     * Four Cases:
302     *
303     * 1. If the arguments indicate unbounded form, act as
304     * nextLong().
305     *
306     * 2. If the range is an exact power of two, apply the
307     * associated bit mask.
308     *
309     * 3. If the range is positive, loop to avoid potential bias
310     * when the implicit nextLong() bound (2<sup>64</sup>) is not
311     * evenly divisible by the range. The loop rejects candidates
312     * computed from otherwise over-represented values. The
313     * expected number of iterations under an ideal generator
314 dl 1.4 * varies from 1 to 2, depending on the bound. The loop itself
315     * takes an unlovable form. Because the first candidate is
316     * already available, we need a break-in-the-middle
317     * construction, which is concisely but cryptically performed
318     * within the while-condition of a body-less for loop.
319 dl 1.1 *
320     * 4. Otherwise, the range cannot be represented as a positive
321 dl 1.4 * long. The loop repeatedly generates unbounded longs until
322     * obtaining a candidate meeting constraints (with an expected
323     * number of iterations of less than two).
324 dl 1.1 */
325    
326     long r = mix64(nextSeed());
327     if (origin < bound) {
328     long n = bound - origin, m = n - 1;
329     if ((n & m) == 0L) // power of two
330     r = (r & m) + origin;
331     else if (n > 0) { // reject over-represented candidates
332     for (long u = r >>> 1; // ensure nonnegative
333     u + m - (r = u % n) < 0L; // reject
334     u = mix64(nextSeed()) >>> 1) // retry
335     ;
336     r += origin;
337     }
338     else { // range not representable as long
339     while (r < origin || r >= bound)
340     r = mix64(nextSeed());
341     }
342     }
343     return r;
344     }
345    
346     /**
347     * The form of nextInt used by IntStream Spliterators.
348     * Exactly the same as long version, except for types.
349     *
350     * @param origin the least value, unless greater than bound
351     * @param bound the upper bound (exclusive), must not equal origin
352     * @return a pseudorandom value
353     */
354     final int internalNextInt(int origin, int bound) {
355     int r = mix32(nextSeed());
356     if (origin < bound) {
357     int n = bound - origin, m = n - 1;
358     if ((n & m) == 0L)
359     r = (r & m) + origin;
360     else if (n > 0) {
361     for (int u = r >>> 1;
362     u + m - (r = u % n) < 0L;
363     u = mix32(nextSeed()) >>> 1)
364     ;
365     r += origin;
366     }
367     else {
368     while (r < origin || r >= bound)
369     r = mix32(nextSeed());
370     }
371     }
372     return r;
373     }
374    
375     /**
376     * The form of nextDouble used by DoubleStream Spliterators.
377     *
378     * @param origin the least value, unless greater than bound
379     * @param bound the upper bound (exclusive), must not equal origin
380     * @return a pseudorandom value
381     */
382     final double internalNextDouble(double origin, double bound) {
383     long bits = (1023L << 52) | (nextLong() >>> 12);
384     double r = Double.longBitsToDouble(bits) - 1.0;
385     if (origin < bound) {
386     r = r * (bound - origin) + origin;
387     if (r == bound) // correct for rounding
388     r = Double.longBitsToDouble(Double.doubleToLongBits(bound) - 1);
389     }
390     return r;
391     }
392    
393     /* ---------------- public methods ---------------- */
394    
395     /**
396     * Creates a new SplittableRandom instance using the given initial
397     * seed. Two SplittableRandom instances created with the same seed
398     * generate identical sequences of values.
399     *
400     * @param seed the initial seed
401     */
402     public SplittableRandom(long seed) {
403     this(seed, 0);
404     }
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     public SplittableRandom() {
413     this(nextDefaultSeed(), GAMMA_GAMMA);
414     }
415    
416     /**
417     * Constructs and returns a new SplittableRandom instance that
418     * shares no mutable state with this instance. However, with very
419     * high probability, the set of values collectively generated by
420     * the two objects has the same statistical properties as if the
421     * same quantity of values were generated by a single thread using
422     * a single SplittableRandom object. Either or both of the two
423     * objects may be further split using the {@code split()} method,
424     * and the same expected statistical properties apply to the
425     * entire set of generators constructed by such recursive
426     * splitting.
427     *
428     * @return the new SplittableRandom instance
429     */
430     public SplittableRandom split() {
431     return new SplittableRandom(nextSeed(), nextSplit);
432     }
433    
434     /**
435     * Returns a pseudorandom {@code int} value.
436     *
437     * @return a pseudorandom value
438     */
439     public int nextInt() {
440     return mix32(nextSeed());
441     }
442    
443     /**
444     * Returns a pseudorandom {@code int} value between 0 (inclusive)
445     * and the specified bound (exclusive).
446     *
447     * @param bound the bound on the random number to be returned. Must be
448     * positive.
449     * @return a pseudorandom {@code int} value between {@code 0}
450     * (inclusive) and the bound (exclusive).
451     * @exception IllegalArgumentException if the bound is not positive
452     */
453     public int nextInt(int bound) {
454     if (bound <= 0)
455     throw new IllegalArgumentException("bound must be positive");
456     // Specialize internalNextInt for origin 0
457     int r = mix32(nextSeed());
458     int m = bound - 1;
459     if ((bound & m) == 0L) // power of two
460     r &= m;
461     else { // reject over-represented candidates
462     for (int u = r >>> 1;
463     u + m - (r = u % bound) < 0L;
464     u = mix32(nextSeed()) >>> 1)
465     ;
466     }
467     return r;
468     }
469    
470     /**
471     * Returns a pseudorandom {@code int} value between the specified
472     * origin (inclusive) and the specified bound (exclusive).
473     *
474     * @param origin the least value returned
475     * @param bound the upper bound (exclusive)
476     * @return a pseudorandom {@code int} value between the origin
477     * (inclusive) and the bound (exclusive).
478     * @exception IllegalArgumentException if {@code origin} is greater than
479     * or equal to {@code bound}
480     */
481     public int nextInt(int origin, int bound) {
482     if (origin >= bound)
483     throw new IllegalArgumentException("bound must be greater than origin");
484     return internalNextInt(origin, bound);
485     }
486    
487     /**
488     * Returns a pseudorandom {@code long} value.
489     *
490     * @return a pseudorandom value
491     */
492     public long nextLong() {
493     return mix64(nextSeed());
494     }
495    
496     /**
497     * Returns a pseudorandom {@code long} value between 0 (inclusive)
498     * and the specified bound (exclusive).
499     *
500     * @param bound the bound on the random number to be returned. Must be
501     * positive.
502     * @return a pseudorandom {@code long} value between {@code 0}
503     * (inclusive) and the bound (exclusive).
504     * @exception IllegalArgumentException if the bound is not positive
505     */
506     public long nextLong(long bound) {
507     if (bound <= 0)
508     throw new IllegalArgumentException("bound must be positive");
509     // 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     * (inclusive) and the bound (exclusive).
531     * @exception IllegalArgumentException if {@code origin} is greater than
532     * or equal to {@code bound}
533     */
534     public long nextLong(long origin, long bound) {
535     if (origin >= bound)
536     throw new IllegalArgumentException("bound must be greater than origin");
537     return internalNextLong(origin, bound);
538     }
539    
540     /**
541     * Returns a pseudorandom {@code double} value between {@code 0.0}
542     * (inclusive) and {@code 1.0} (exclusive).
543     *
544     * @return a pseudorandom value between {@code 0.0}
545     * (inclusive) and {@code 1.0} (exclusive)
546     */
547     public double nextDouble() {
548     long bits = (1023L << 52) | (nextLong() >>> 12);
549     return Double.longBitsToDouble(bits) - 1.0;
550     }
551    
552     /**
553     * Returns a pseudorandom {@code double} value between 0.0
554     * (inclusive) and the specified bound (exclusive).
555     *
556     * @param bound the bound on the random number to be returned. Must be
557     * positive.
558     * @return a pseudorandom {@code double} value between {@code 0.0}
559     * (inclusive) and the bound (exclusive).
560     * @throws IllegalArgumentException if {@code bound} is not positive
561     */
562     public double nextDouble(double bound) {
563     if (bound <= 0.0)
564     throw new IllegalArgumentException("bound must be positive");
565     double result = nextDouble() * bound;
566     return (result < bound) ? result : // correct for rounding
567     Double.longBitsToDouble(Double.doubleToLongBits(bound) - 1);
568     }
569    
570     /**
571     * Returns a pseudorandom {@code double} value between the given
572     * origin (inclusive) and bound (exclusive).
573     *
574     * @param origin the least value returned
575     * @param bound the upper bound
576     * @return a pseudorandom {@code double} value between the origin
577     * (inclusive) and the bound (exclusive).
578     * @throws IllegalArgumentException if {@code origin} is greater than
579     * or equal to {@code bound}
580     */
581     public double nextDouble(double origin, double bound) {
582     if (origin >= bound)
583     throw new IllegalArgumentException("bound must be greater than origin");
584     return internalNextDouble(origin, bound);
585     }
586    
587     // stream methods, coded in a way intended to better isolate for
588     // maintenance purposes the small differences across forms.
589    
590     /**
591     * Returns a stream with the given {@code streamSize} number of
592     * pseudorandom {@code int} values.
593     *
594     * @param streamSize the number of values to generate
595     * @return a stream of pseudorandom {@code int} values
596     * @throws IllegalArgumentException if {@code streamSize} is
597     * less than zero
598     */
599     public IntStream ints(long streamSize) {
600     if (streamSize < 0L)
601     throw new IllegalArgumentException("negative Stream size");
602     return StreamSupport.intStream
603     (new RandomIntsSpliterator
604     (this, 0L, streamSize, Integer.MAX_VALUE, 0),
605     false);
606     }
607    
608     /**
609     * Returns an effectively unlimited stream of pseudorandom {@code int}
610     * values
611     *
612     * @implNote This method is implemented to be equivalent to {@code
613     * ints(Long.MAX_VALUE)}.
614     *
615     * @return a stream of pseudorandom {@code int} values
616     */
617     public IntStream ints() {
618     return StreamSupport.intStream
619     (new RandomIntsSpliterator
620     (this, 0L, Long.MAX_VALUE, Integer.MAX_VALUE, 0),
621     false);
622     }
623    
624     /**
625     * Returns a stream with the given {@code streamSize} number of
626     * pseudorandom {@code int} values, each conforming to the given
627     * origin and bound.
628     *
629     * @param streamSize the number of values to generate
630     * @param randomNumberOrigin the origin of each random value
631     * @param randomNumberBound the bound of each random value
632     * @return a stream of pseudorandom {@code int} values,
633     * each with the given origin and bound.
634     * @throws IllegalArgumentException if {@code streamSize} is
635     * less than zero.
636     * @throws IllegalArgumentException if {@code randomNumberOrigin}
637     * is greater than or equal to {@code randomNumberBound}
638     */
639     public IntStream ints(long streamSize, int randomNumberOrigin,
640     int randomNumberBound) {
641     if (streamSize < 0L)
642     throw new IllegalArgumentException("negative Stream size");
643     if (randomNumberOrigin >= randomNumberBound)
644     throw new IllegalArgumentException("bound must be greater than origin");
645     return StreamSupport.intStream
646     (new RandomIntsSpliterator
647     (this, 0L, streamSize, randomNumberOrigin, randomNumberBound),
648     false);
649     }
650    
651     /**
652     * Returns an effectively unlimited stream of pseudorandom {@code
653     * int} values, each conforming to the given origin and bound.
654     *
655     * @implNote This method is implemented to be equivalent to {@code
656     * ints(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
657     *
658     * @param randomNumberOrigin the origin of each random value
659     * @param randomNumberBound the bound of each random value
660     * @return a stream of pseudorandom {@code int} values,
661     * each with the given origin and bound.
662     * @throws IllegalArgumentException if {@code randomNumberOrigin}
663     * is greater than or equal to {@code randomNumberBound}
664     */
665     public IntStream ints(int randomNumberOrigin, int randomNumberBound) {
666     if (randomNumberOrigin >= randomNumberBound)
667     throw new IllegalArgumentException("bound must be greater than origin");
668     return StreamSupport.intStream
669     (new RandomIntsSpliterator
670     (this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
671     false);
672     }
673    
674     /**
675     * Returns a stream with the given {@code streamSize} number of
676     * pseudorandom {@code long} values.
677     *
678     * @param streamSize the number of values to generate
679     * @return a stream of {@code long} values
680     * @throws IllegalArgumentException if {@code streamSize} is
681     * less than zero
682     */
683     public LongStream longs(long streamSize) {
684     if (streamSize < 0L)
685     throw new IllegalArgumentException("negative Stream size");
686     return StreamSupport.longStream
687     (new RandomLongsSpliterator
688     (this, 0L, streamSize, Long.MAX_VALUE, 0L),
689     false);
690     }
691    
692     /**
693     * Returns an effectively unlimited stream of pseudorandom {@code long}
694     * values.
695     *
696     * @implNote This method is implemented to be equivalent to {@code
697     * longs(Long.MAX_VALUE)}.
698     *
699     * @return a stream of pseudorandom {@code long} values
700     */
701     public LongStream longs() {
702     return StreamSupport.longStream
703     (new RandomLongsSpliterator
704     (this, 0L, Long.MAX_VALUE, Long.MAX_VALUE, 0L),
705     false);
706     }
707    
708     /**
709     * Returns a stream with the given {@code streamSize} number of
710     * pseudorandom {@code long} values, each conforming to the
711     * given origin and bound.
712     *
713     * @param streamSize the number of values to generate
714     * @param randomNumberOrigin the origin of each random value
715     * @param randomNumberBound the bound of each random value
716     * @return a stream of pseudorandom {@code long} values,
717     * each with the given origin and bound.
718     * @throws IllegalArgumentException if {@code streamSize} is
719     * less than zero.
720     * @throws IllegalArgumentException if {@code randomNumberOrigin}
721     * is greater than or equal to {@code randomNumberBound}
722     */
723     public LongStream longs(long streamSize, long randomNumberOrigin,
724     long randomNumberBound) {
725     if (streamSize < 0L)
726     throw new IllegalArgumentException("negative Stream size");
727     if (randomNumberOrigin >= randomNumberBound)
728     throw new IllegalArgumentException("bound must be greater than origin");
729     return StreamSupport.longStream
730     (new RandomLongsSpliterator
731     (this, 0L, streamSize, randomNumberOrigin, randomNumberBound),
732     false);
733     }
734    
735     /**
736     * Returns an effectively unlimited stream of pseudorandom {@code
737     * long} values, each conforming to the given origin and bound.
738     *
739     * @implNote This method is implemented to be equivalent to {@code
740     * longs(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
741     *
742     * @param randomNumberOrigin the origin of each random value
743     * @param randomNumberBound the bound of each random value
744     * @return a stream of pseudorandom {@code long} values,
745     * each with the given origin and bound.
746     * @throws IllegalArgumentException if {@code randomNumberOrigin}
747     * is greater than or equal to {@code randomNumberBound}
748     */
749     public LongStream longs(long randomNumberOrigin, long randomNumberBound) {
750     if (randomNumberOrigin >= randomNumberBound)
751     throw new IllegalArgumentException("bound must be greater than origin");
752     return StreamSupport.longStream
753     (new RandomLongsSpliterator
754     (this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
755     false);
756     }
757    
758     /**
759     * Returns a stream with the given {@code streamSize} number of
760 dl 1.2 * pseudorandom {@code double} values, each between {@code 0.0}
761     * (inclusive) and {@code 1.0} (exclusive).
762 dl 1.1 *
763     * @param streamSize the number of values to generate
764     * @return a stream of {@code double} values
765     * @throws IllegalArgumentException if {@code streamSize} is
766     * less than zero
767     */
768     public DoubleStream doubles(long streamSize) {
769     if (streamSize < 0L)
770     throw new IllegalArgumentException("negative Stream size");
771     return StreamSupport.doubleStream
772     (new RandomDoublesSpliterator
773     (this, 0L, streamSize, Double.MAX_VALUE, 0.0),
774     false);
775     }
776    
777     /**
778     * Returns an effectively unlimited stream of pseudorandom {@code
779 dl 1.2 * double} values, each between {@code 0.0} (inclusive) and {@code
780     * 1.0} (exclusive).
781 dl 1.1 *
782     * @implNote This method is implemented to be equivalent to {@code
783     * doubles(Long.MAX_VALUE)}.
784     *
785     * @return a stream of pseudorandom {@code double} values
786     */
787     public DoubleStream doubles() {
788     return StreamSupport.doubleStream
789     (new RandomDoublesSpliterator
790     (this, 0L, Long.MAX_VALUE, Double.MAX_VALUE, 0.0),
791     false);
792     }
793    
794     /**
795     * Returns a stream with the given {@code streamSize} number of
796     * pseudorandom {@code double} values, each conforming to the
797     * given origin and bound.
798     *
799     * @param streamSize the number of values to generate
800     * @param randomNumberOrigin the origin of each random value
801     * @param randomNumberBound the bound of each random value
802     * @return a stream of pseudorandom {@code double} values,
803     * each with the given origin and bound.
804     * @throws IllegalArgumentException if {@code streamSize} is
805     * less than zero.
806     * @throws IllegalArgumentException if {@code randomNumberOrigin}
807     * is greater than or equal to {@code randomNumberBound}
808     */
809     public DoubleStream doubles(long streamSize, double randomNumberOrigin,
810     double randomNumberBound) {
811     if (streamSize < 0L)
812     throw new IllegalArgumentException("negative Stream size");
813     if (randomNumberOrigin >= randomNumberBound)
814     throw new IllegalArgumentException("bound must be greater than origin");
815     return StreamSupport.doubleStream
816     (new RandomDoublesSpliterator
817     (this, 0L, streamSize, randomNumberOrigin, randomNumberBound),
818     false);
819     }
820    
821     /**
822     * Returns an effectively unlimited stream of pseudorandom {@code
823     * double} values, each conforming to the given origin and bound.
824     *
825     * @implNote This method is implemented to be equivalent to {@code
826     * doubles(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
827     *
828     * @param randomNumberOrigin the origin of each random value
829     * @param randomNumberBound the bound of each random value
830     * @return a stream of pseudorandom {@code double} values,
831     * each with the given origin and bound.
832     * @throws IllegalArgumentException if {@code randomNumberOrigin}
833     * is greater than or equal to {@code randomNumberBound}
834     */
835     public DoubleStream doubles(double randomNumberOrigin, double randomNumberBound) {
836     if (randomNumberOrigin >= randomNumberBound)
837     throw new IllegalArgumentException("bound must be greater than origin");
838     return StreamSupport.doubleStream
839     (new RandomDoublesSpliterator
840     (this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
841     false);
842     }
843    
844     /**
845     * Spliterator for int streams. We multiplex the four int
846     * versions into one class by treating and bound < origin as
847     * unbounded, and also by treating "infinite" as equivalent to
848     * Long.MAX_VALUE. For splits, it uses the standard divide-by-two
849     * approach. The long and double versions of this class are
850     * identical except for types.
851     */
852     static class RandomIntsSpliterator implements Spliterator.OfInt {
853     final SplittableRandom rng;
854     long index;
855     final long fence;
856     final int origin;
857     final int bound;
858     RandomIntsSpliterator(SplittableRandom rng, long index, long fence,
859     int origin, int bound) {
860     this.rng = rng; this.index = index; this.fence = fence;
861     this.origin = origin; this.bound = bound;
862     }
863    
864     public RandomIntsSpliterator trySplit() {
865     long i = index, m = (i + fence) >>> 1;
866     return (m <= i) ? null :
867     new RandomIntsSpliterator(rng.split(), i, index = m, origin, bound);
868     }
869    
870     public long estimateSize() {
871     return fence - index;
872     }
873    
874     public int characteristics() {
875     return (Spliterator.SIZED | Spliterator.SUBSIZED |
876 dl 1.4 Spliterator.NONNULL | Spliterator.IMMUTABLE);
877 dl 1.1 }
878    
879     public boolean tryAdvance(IntConsumer consumer) {
880     if (consumer == null) throw new NullPointerException();
881     long i = index, f = fence;
882     if (i < f) {
883     consumer.accept(rng.internalNextInt(origin, bound));
884     index = i + 1;
885     return true;
886     }
887     return false;
888     }
889    
890     public void forEachRemaining(IntConsumer consumer) {
891     if (consumer == null) throw new NullPointerException();
892     long i = index, f = fence;
893     if (i < f) {
894     index = f;
895     int o = origin, b = bound;
896     do {
897     consumer.accept(rng.internalNextInt(o, b));
898     } while (++i < f);
899     }
900     }
901     }
902    
903     /**
904     * Spliterator for long streams.
905     */
906     static class RandomLongsSpliterator implements Spliterator.OfLong {
907     final SplittableRandom rng;
908     long index;
909     final long fence;
910     final long origin;
911     final long bound;
912     RandomLongsSpliterator(SplittableRandom rng, long index, long fence,
913     long origin, long bound) {
914     this.rng = rng; this.index = index; this.fence = fence;
915     this.origin = origin; this.bound = bound;
916     }
917    
918     public RandomLongsSpliterator trySplit() {
919     long i = index, m = (i + fence) >>> 1;
920     return (m <= i) ? null :
921     new RandomLongsSpliterator(rng.split(), i, index = m, origin, bound);
922     }
923    
924     public long estimateSize() {
925     return fence - index;
926     }
927    
928     public int characteristics() {
929     return (Spliterator.SIZED | Spliterator.SUBSIZED |
930 dl 1.4 Spliterator.NONNULL | Spliterator.IMMUTABLE);
931 dl 1.1 }
932    
933     public boolean tryAdvance(LongConsumer consumer) {
934     if (consumer == null) throw new NullPointerException();
935     long i = index, f = fence;
936     if (i < f) {
937     consumer.accept(rng.internalNextLong(origin, bound));
938     index = i + 1;
939     return true;
940     }
941     return false;
942     }
943    
944     public void forEachRemaining(LongConsumer consumer) {
945     if (consumer == null) throw new NullPointerException();
946     long i = index, f = fence;
947     if (i < f) {
948     index = f;
949     long o = origin, b = bound;
950     do {
951     consumer.accept(rng.internalNextLong(o, b));
952     } while (++i < f);
953     }
954     }
955    
956     }
957    
958     /**
959     * Spliterator for double streams.
960     */
961     static class RandomDoublesSpliterator implements Spliterator.OfDouble {
962     final SplittableRandom rng;
963     long index;
964     final long fence;
965     final double origin;
966     final double bound;
967     RandomDoublesSpliterator(SplittableRandom rng, long index, long fence,
968     double origin, double bound) {
969     this.rng = rng; this.index = index; this.fence = fence;
970     this.origin = origin; this.bound = bound;
971     }
972    
973     public RandomDoublesSpliterator trySplit() {
974     long i = index, m = (i + fence) >>> 1;
975     return (m <= i) ? null :
976     new RandomDoublesSpliterator(rng.split(), i, index = m, origin, bound);
977     }
978    
979     public long estimateSize() {
980     return fence - index;
981     }
982    
983     public int characteristics() {
984     return (Spliterator.SIZED | Spliterator.SUBSIZED |
985 dl 1.4 Spliterator.NONNULL | Spliterator.IMMUTABLE);
986 dl 1.1 }
987    
988     public boolean tryAdvance(DoubleConsumer consumer) {
989     if (consumer == null) throw new NullPointerException();
990     long i = index, f = fence;
991     if (i < f) {
992     consumer.accept(rng.internalNextDouble(origin, bound));
993     index = i + 1;
994     return true;
995     }
996     return false;
997     }
998    
999     public void forEachRemaining(DoubleConsumer consumer) {
1000     if (consumer == null) throw new NullPointerException();
1001     long i = index, f = fence;
1002     if (i < f) {
1003     index = f;
1004     double o = origin, b = bound;
1005     do {
1006     consumer.accept(rng.internalNextDouble(o, b));
1007     } while (++i < f);
1008     }
1009     }
1010     }
1011    
1012     }
1013