ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/SplittableRandom.java
Revision: 1.12
Committed: Sun Jul 21 14:02:23 2013 UTC (10 years, 9 months ago) by dl
Branch: MAIN
Changes since 1.11: +29 -30 lines
Log Message:
Use SecureRandom initial default seed; misc wording updates

File Contents

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