[cvs] / jsr166 / src / main / java / util / SplittableRandom.java Repository:
ViewVC logotype

Annotation of /jsr166/src/main/java/util/SplittableRandom.java

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.3 - (view) (download)

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 :     * varies from 1 to 2, depending on the bound.
315 :     *
316 :     * 4. Otherwise, the range cannot be represented as a positive
317 :     * long. Repeatedly generate unbounded longs until obtaining
318 :     * a candidate meeting constraints (with an expected number of
319 :     * iterations of less than two).
320 :     */
321 :    
322 :     long r = mix64(nextSeed());
323 :     if (origin < bound) {
324 :     long n = bound - origin, m = n - 1;
325 :     if ((n & m) == 0L) // power of two
326 :     r = (r & m) + origin;
327 :     else if (n > 0) { // reject over-represented candidates
328 :     for (long u = r >>> 1; // ensure nonnegative
329 :     u + m - (r = u % n) < 0L; // reject
330 :     u = mix64(nextSeed()) >>> 1) // retry
331 :     ;
332 :     r += origin;
333 :     }
334 :     else { // range not representable as long
335 :     while (r < origin || r >= bound)
336 :     r = mix64(nextSeed());
337 :     }
338 :     }
339 :     return r;
340 :     }
341 :    
342 :     /**
343 :     * The form of nextInt used by IntStream Spliterators.
344 :     * Exactly the same as long version, except for types.
345 :     *
346 :     * @param origin the least value, unless greater than bound
347 :     * @param bound the upper bound (exclusive), must not equal origin
348 :     * @return a pseudorandom value
349 :     */
350 :     final int internalNextInt(int origin, int bound) {
351 :     int r = mix32(nextSeed());
352 :     if (origin < bound) {
353 :     int n = bound - origin, m = n - 1;
354 :     if ((n & m) == 0L)
355 :     r = (r & m) + origin;
356 :     else if (n > 0) {
357 :     for (int u = r >>> 1;
358 :     u + m - (r = u % n) < 0L;
359 :     u = mix32(nextSeed()) >>> 1)
360 :     ;
361 :     r += origin;
362 :     }
363 :     else {
364 :     while (r < origin || r >= bound)
365 :     r = mix32(nextSeed());
366 :     }
367 :     }
368 :     return r;
369 :     }
370 :    
371 :     /**
372 :     * The form of nextDouble used by DoubleStream Spliterators.
373 :     *
374 :     * @param origin the least value, unless greater than bound
375 :     * @param bound the upper bound (exclusive), must not equal origin
376 :     * @return a pseudorandom value
377 :     */
378 :     final double internalNextDouble(double origin, double bound) {
379 :     long bits = (1023L << 52) | (nextLong() >>> 12);
380 :     double r = Double.longBitsToDouble(bits) - 1.0;
381 :     if (origin < bound) {
382 :     r = r * (bound - origin) + origin;
383 :     if (r == bound) // correct for rounding
384 :     r = Double.longBitsToDouble(Double.doubleToLongBits(bound) - 1);
385 :     }
386 :     return r;
387 :     }
388 :    
389 :     /* ---------------- public methods ---------------- */
390 :    
391 :     /**
392 :     * Creates a new SplittableRandom instance using the given initial
393 :     * seed. Two SplittableRandom instances created with the same seed
394 :     * generate identical sequences of values.
395 :     *
396 :     * @param seed the initial seed
397 :     */
398 :     public SplittableRandom(long seed) {
399 :     this(seed, 0);
400 :     }
401 :    
402 :     /**
403 :     * Creates a new SplittableRandom instance that is likely to
404 :     * generate sequences of values that are statistically independent
405 :     * of those of any other instances in the current program; and
406 :     * may, and typically does, vary across program invocations.
407 :     */
408 :     public SplittableRandom() {
409 :     this(nextDefaultSeed(), GAMMA_GAMMA);
410 :     }
411 :    
412 :     /**
413 :     * Constructs and returns a new SplittableRandom instance that
414 :     * shares no mutable state with this instance. However, with very
415 :     * high probability, the set of values collectively generated by
416 :     * the two objects has the same statistical properties as if the
417 :     * same quantity of values were generated by a single thread using
418 :     * a single SplittableRandom object. Either or both of the two
419 :     * objects may be further split using the {@code split()} method,
420 :     * and the same expected statistical properties apply to the
421 :     * entire set of generators constructed by such recursive
422 :     * splitting.
423 :     *
424 :     * @return the new SplittableRandom instance
425 :     */
426 :     public SplittableRandom split() {
427 :     return new SplittableRandom(nextSeed(), nextSplit);
428 :     }
429 :    
430 :     /**
431 :     * Returns a pseudorandom {@code int} value.
432 :     *
433 :     * @return a pseudorandom value
434 :     */
435 :     public int nextInt() {
436 :     return mix32(nextSeed());
437 :     }
438 :    
439 :     /**
440 :     * Returns a pseudorandom {@code int} value between 0 (inclusive)
441 :     * and the specified bound (exclusive).
442 :     *
443 :     * @param bound the bound on the random number to be returned. Must be
444 :     * positive.
445 :     * @return a pseudorandom {@code int} value between {@code 0}
446 :     * (inclusive) and the bound (exclusive).
447 :     * @exception IllegalArgumentException if the bound is not positive
448 :     */
449 :     public int nextInt(int bound) {
450 :     if (bound <= 0)
451 :     throw new IllegalArgumentException("bound must be positive");
452 :     // Specialize internalNextInt for origin 0
453 :     int r = mix32(nextSeed());
454 :     int m = bound - 1;
455 :     if ((bound & m) == 0L) // power of two
456 :     r &= m;
457 :     else { // reject over-represented candidates
458 :     for (int u = r >>> 1;
459 :     u + m - (r = u % bound) < 0L;
460 :     u = mix32(nextSeed()) >>> 1)
461 :     ;
462 :     }
463 :     return r;
464 :     }
465 :    
466 :     /**
467 :     * Returns a pseudorandom {@code int} value between the specified
468 :     * origin (inclusive) and the specified bound (exclusive).
469 :     *
470 :     * @param origin the least value returned
471 :     * @param bound the upper bound (exclusive)
472 :     * @return a pseudorandom {@code int} value between the origin
473 :     * (inclusive) and the bound (exclusive).
474 :     * @exception IllegalArgumentException if {@code origin} is greater than
475 :     * or equal to {@code bound}
476 :     */
477 :     public int nextInt(int origin, int bound) {
478 :     if (origin >= bound)
479 :     throw new IllegalArgumentException("bound must be greater than origin");
480 :     return internalNextInt(origin, bound);
481 :     }
482 :    
483 :     /**
484 :     * Returns a pseudorandom {@code long} value.
485 :     *
486 :     * @return a pseudorandom value
487 :     */
488 :     public long nextLong() {
489 :     return mix64(nextSeed());
490 :     }
491 :    
492 :     /**
493 :     * Returns a pseudorandom {@code long} value between 0 (inclusive)
494 :     * and the specified bound (exclusive).
495 :     *
496 :     * @param bound the bound on the random number to be returned. Must be
497 :     * positive.
498 :     * @return a pseudorandom {@code long} value between {@code 0}
499 :     * (inclusive) and the bound (exclusive).
500 :     * @exception IllegalArgumentException if the bound is not positive
501 :     */
502 :     public long nextLong(long bound) {
503 :     if (bound <= 0)
504 :     throw new IllegalArgumentException("bound must be positive");
505 :     // Specialize internalNextLong for origin 0
506 :     long r = mix64(nextSeed());
507 :     long m = bound - 1;
508 :     if ((bound & m) == 0L) // power of two
509 :     r &= m;
510 :     else { // reject over-represented candidates
511 :     for (long u = r >>> 1;
512 :     u + m - (r = u % bound) < 0L;
513 :     u = mix64(nextSeed()) >>> 1)
514 :     ;
515 :     }
516 :     return r;
517 :     }
518 :    
519 :     /**
520 :     * Returns a pseudorandom {@code long} value between the specified
521 :     * origin (inclusive) and the specified bound (exclusive).
522 :     *
523 :     * @param origin the least value returned
524 :     * @param bound the upper bound (exclusive)
525 :     * @return a pseudorandom {@code long} value between the origin
526 :     * (inclusive) and the bound (exclusive).
527 :     * @exception IllegalArgumentException if {@code origin} is greater than
528 :     * or equal to {@code bound}
529 :     */
530 :     public long nextLong(long origin, long bound) {
531 :     if (origin >= bound)
532 :     throw new IllegalArgumentException("bound must be greater than origin");
533 :     return internalNextLong(origin, bound);
534 :     }
535 :    
536 :     /**
537 :     * Returns a pseudorandom {@code double} value between {@code 0.0}
538 :     * (inclusive) and {@code 1.0} (exclusive).
539 :     *
540 :     * @return a pseudorandom value between {@code 0.0}
541 :     * (inclusive) and {@code 1.0} (exclusive)
542 :     */
543 :     public double nextDouble() {
544 :     long bits = (1023L << 52) | (nextLong() >>> 12);
545 :     return Double.longBitsToDouble(bits) - 1.0;
546 :     }
547 :    
548 :     /**
549 :     * Returns a pseudorandom {@code double} value between 0.0
550 :     * (inclusive) and the specified bound (exclusive).
551 :     *
552 :     * @param bound the bound on the random number to be returned. Must be
553 :     * positive.
554 :     * @return a pseudorandom {@code double} value between {@code 0.0}
555 :     * (inclusive) and the bound (exclusive).
556 :     * @throws IllegalArgumentException if {@code bound} is not positive
557 :     */
558 :     public double nextDouble(double bound) {
559 :     if (bound <= 0.0)
560 :     throw new IllegalArgumentException("bound must be positive");
561 :     double result = nextDouble() * bound;
562 :     return (result < bound) ? result : // correct for rounding
563 :     Double.longBitsToDouble(Double.doubleToLongBits(bound) - 1);
564 :     }
565 :    
566 :     /**
567 :     * Returns a pseudorandom {@code double} value between the given
568 :     * origin (inclusive) and bound (exclusive).
569 :     *
570 :     * @param origin the least value returned
571 :     * @param bound the upper bound
572 :     * @return a pseudorandom {@code double} value between the origin
573 :     * (inclusive) and the bound (exclusive).
574 :     * @throws IllegalArgumentException if {@code origin} is greater than
575 :     * or equal to {@code bound}
576 :     */
577 :     public double nextDouble(double origin, double bound) {
578 :     if (origin >= bound)
579 :     throw new IllegalArgumentException("bound must be greater than origin");
580 :     return internalNextDouble(origin, bound);
581 :     }
582 :    
583 :     // stream methods, coded in a way intended to better isolate for
584 :     // maintenance purposes the small differences across forms.
585 :    
586 :     /**
587 :     * Returns a stream with the given {@code streamSize} number of
588 :     * pseudorandom {@code int} values.
589 :     *
590 :     * @param streamSize the number of values to generate
591 :     * @return a stream of pseudorandom {@code int} values
592 :     * @throws IllegalArgumentException if {@code streamSize} is
593 :     * less than zero
594 :     */
595 :     public IntStream ints(long streamSize) {
596 :     if (streamSize < 0L)
597 :     throw new IllegalArgumentException("negative Stream size");
598 :     return StreamSupport.intStream
599 :     (new RandomIntsSpliterator
600 :     (this, 0L, streamSize, Integer.MAX_VALUE, 0),
601 :     false);
602 :     }
603 :    
604 :     /**
605 :     * Returns an effectively unlimited stream of pseudorandom {@code int}
606 :     * values
607 :     *
608 :     * @implNote This method is implemented to be equivalent to {@code
609 :     * ints(Long.MAX_VALUE)}.
610 :     *
611 :     * @return a stream of pseudorandom {@code int} values
612 :     */
613 :     public IntStream ints() {
614 :     return StreamSupport.intStream
615 :     (new RandomIntsSpliterator
616 :     (this, 0L, Long.MAX_VALUE, Integer.MAX_VALUE, 0),
617 :     false);
618 :     }
619 :    
620 :     /**
621 :     * Returns a stream with the given {@code streamSize} number of
622 :     * pseudorandom {@code int} values, each conforming to the given
623 :     * origin and bound.
624 :     *
625 :     * @param streamSize the number of values to generate
626 :     * @param randomNumberOrigin the origin of each random value
627 :     * @param randomNumberBound the bound of each random value
628 :     * @return a stream of pseudorandom {@code int} values,
629 :     * each with the given origin and bound.
630 :     * @throws IllegalArgumentException if {@code streamSize} is
631 :     * less than zero.
632 :     * @throws IllegalArgumentException if {@code randomNumberOrigin}
633 :     * is greater than or equal to {@code randomNumberBound}
634 :     */
635 :     public IntStream ints(long streamSize, int randomNumberOrigin,
636 :     int randomNumberBound) {
637 :     if (streamSize < 0L)
638 :     throw new IllegalArgumentException("negative Stream size");
639 :     if (randomNumberOrigin >= randomNumberBound)
640 :     throw new IllegalArgumentException("bound must be greater than origin");
641 :     return StreamSupport.intStream
642 :     (new RandomIntsSpliterator
643 :     (this, 0L, streamSize, randomNumberOrigin, randomNumberBound),
644 :     false);
645 :     }
646 :    
647 :     /**
648 :     * Returns an effectively unlimited stream of pseudorandom {@code
649 :     * int} values, each conforming to the given origin and bound.
650 :     *
651 :     * @implNote This method is implemented to be equivalent to {@code
652 :     * ints(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
653 :     *
654 :     * @param randomNumberOrigin the origin of each random value
655 :     * @param randomNumberBound the bound of each random value
656 :     * @return a stream of pseudorandom {@code int} values,
657 :     * each with the given origin and bound.
658 :     * @throws IllegalArgumentException if {@code randomNumberOrigin}
659 :     * is greater than or equal to {@code randomNumberBound}
660 :     */
661 :     public IntStream ints(int randomNumberOrigin, int randomNumberBound) {
662 :     if (randomNumberOrigin >= randomNumberBound)
663 :     throw new IllegalArgumentException("bound must be greater than origin");
664 :     return StreamSupport.intStream
665 :     (new RandomIntsSpliterator
666 :     (this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
667 :     false);
668 :     }
669 :    
670 :     /**
671 :     * Returns a stream with the given {@code streamSize} number of
672 :     * pseudorandom {@code long} values.
673 :     *
674 :     * @param streamSize the number of values to generate
675 :     * @return a stream of {@code long} values
676 :     * @throws IllegalArgumentException if {@code streamSize} is
677 :     * less than zero
678 :     */
679 :     public LongStream longs(long streamSize) {
680 :     if (streamSize < 0L)
681 :     throw new IllegalArgumentException("negative Stream size");
682 :     return StreamSupport.longStream
683 :     (new RandomLongsSpliterator
684 :     (this, 0L, streamSize, Long.MAX_VALUE, 0L),
685 :     false);
686 :     }
687 :    
688 :     /**
689 :     * Returns an effectively unlimited stream of pseudorandom {@code long}
690 :     * values.
691 :     *
692 :     * @implNote This method is implemented to be equivalent to {@code
693 :     * longs(Long.MAX_VALUE)}.
694 :     *
695 :     * @return a stream of pseudorandom {@code long} values
696 :     */
697 :     public LongStream longs() {
698 :     return StreamSupport.longStream
699 :     (new RandomLongsSpliterator
700 :     (this, 0L, Long.MAX_VALUE, Long.MAX_VALUE, 0L),
701 :     false);
702 :     }
703 :    
704 :     /**
705 :     * Returns a stream with the given {@code streamSize} number of
706 :     * pseudorandom {@code long} values, each conforming to the
707 :     * given origin and bound.
708 :     *
709 :     * @param streamSize the number of values to generate
710 :     * @param randomNumberOrigin the origin of each random value
711 :     * @param randomNumberBound the bound of each random value
712 :     * @return a stream of pseudorandom {@code long} values,
713 :     * each with the given origin and bound.
714 :     * @throws IllegalArgumentException if {@code streamSize} is
715 :     * less than zero.
716 :     * @throws IllegalArgumentException if {@code randomNumberOrigin}
717 :     * is greater than or equal to {@code randomNumberBound}
718 :     */
719 :     public LongStream longs(long streamSize, long randomNumberOrigin,
720 :     long randomNumberBound) {
721 :     if (streamSize < 0L)
722 :     throw new IllegalArgumentException("negative Stream size");
723 :     if (randomNumberOrigin >= randomNumberBound)
724 :     throw new IllegalArgumentException("bound must be greater than origin");
725 :     return StreamSupport.longStream
726 :     (new RandomLongsSpliterator
727 :     (this, 0L, streamSize, randomNumberOrigin, randomNumberBound),
728 :     false);
729 :     }
730 :    
731 :     /**
732 :     * Returns an effectively unlimited stream of pseudorandom {@code
733 :     * long} values, each conforming to the given origin and bound.
734 :     *
735 :     * @implNote This method is implemented to be equivalent to {@code
736 :     * longs(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
737 :     *
738 :     * @param randomNumberOrigin the origin of each random value
739 :     * @param randomNumberBound the bound of each random value
740 :     * @return a stream of pseudorandom {@code long} values,
741 :     * each with the given origin and bound.
742 :     * @throws IllegalArgumentException if {@code randomNumberOrigin}
743 :     * is greater than or equal to {@code randomNumberBound}
744 :     */
745 :     public LongStream longs(long randomNumberOrigin, long randomNumberBound) {
746 :     if (randomNumberOrigin >= randomNumberBound)
747 :     throw new IllegalArgumentException("bound must be greater than origin");
748 :     return StreamSupport.longStream
749 :     (new RandomLongsSpliterator
750 :     (this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
751 :     false);
752 :     }
753 :    
754 :     /**
755 :     * Returns a stream with the given {@code streamSize} number of
756 : dl 1.2 * pseudorandom {@code double} values, each between {@code 0.0}
757 :     * (inclusive) and {@code 1.0} (exclusive).
758 : dl 1.1 *
759 :     * @param streamSize the number of values to generate
760 :     * @return a stream of {@code double} values
761 :     * @throws IllegalArgumentException if {@code streamSize} is
762 :     * less than zero
763 :     */
764 :     public DoubleStream doubles(long streamSize) {
765 :     if (streamSize < 0L)
766 :     throw new IllegalArgumentException("negative Stream size");
767 :     return StreamSupport.doubleStream
768 :     (new RandomDoublesSpliterator
769 :     (this, 0L, streamSize, Double.MAX_VALUE, 0.0),
770 :     false);
771 :     }
772 :    
773 :     /**
774 :     * Returns an effectively unlimited stream of pseudorandom {@code
775 : dl 1.2 * double} values, each between {@code 0.0} (inclusive) and {@code
776 :     * 1.0} (exclusive).
777 : dl 1.1 *
778 :     * @implNote This method is implemented to be equivalent to {@code
779 :     * doubles(Long.MAX_VALUE)}.
780 :     *
781 :     * @return a stream of pseudorandom {@code double} values
782 :     */
783 :     public DoubleStream doubles() {
784 :     return StreamSupport.doubleStream
785 :     (new RandomDoublesSpliterator
786 :     (this, 0L, Long.MAX_VALUE, Double.MAX_VALUE, 0.0),
787 :     false);
788 :     }
789 :    
790 :     /**
791 :     * Returns a stream with the given {@code streamSize} number of
792 :     * pseudorandom {@code double} values, each conforming to the
793 :     * given origin and bound.
794 :     *
795 :     * @param streamSize the number of values to generate
796 :     * @param randomNumberOrigin the origin of each random value
797 :     * @param randomNumberBound the bound of each random value
798 :     * @return a stream of pseudorandom {@code double} values,
799 :     * each with the given origin and bound.
800 :     * @throws IllegalArgumentException if {@code streamSize} is
801 :     * less than zero.
802 :     * @throws IllegalArgumentException if {@code randomNumberOrigin}
803 :     * is greater than or equal to {@code randomNumberBound}
804 :     */
805 :     public DoubleStream doubles(long streamSize, double randomNumberOrigin,
806 :     double randomNumberBound) {
807 :     if (streamSize < 0L)
808 :     throw new IllegalArgumentException("negative Stream size");
809 :     if (randomNumberOrigin >= randomNumberBound)
810 :     throw new IllegalArgumentException("bound must be greater than origin");
811 :     return StreamSupport.doubleStream
812 :     (new RandomDoublesSpliterator
813 :     (this, 0L, streamSize, randomNumberOrigin, randomNumberBound),
814 :     false);
815 :     }
816 :    
817 :     /**
818 :     * Returns an effectively unlimited stream of pseudorandom {@code
819 :     * double} values, each conforming to the given origin and bound.
820 :     *
821 :     * @implNote This method is implemented to be equivalent to {@code
822 :     * doubles(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
823 :     *
824 :     * @param randomNumberOrigin the origin of each random value
825 :     * @param randomNumberBound the bound of each random value
826 :     * @return a stream of pseudorandom {@code double} values,
827 :     * each with the given origin and bound.
828 :     * @throws IllegalArgumentException if {@code randomNumberOrigin}
829 :     * is greater than or equal to {@code randomNumberBound}
830 :     */
831 :     public DoubleStream doubles(double randomNumberOrigin, double randomNumberBound) {
832 :     if (randomNumberOrigin >= randomNumberBound)
833 :     throw new IllegalArgumentException("bound must be greater than origin");
834 :     return StreamSupport.doubleStream
835 :     (new RandomDoublesSpliterator
836 :     (this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
837 :     false);
838 :     }
839 :    
840 :     /**
841 :     * Spliterator for int streams. We multiplex the four int
842 :     * versions into one class by treating and bound < origin as
843 :     * unbounded, and also by treating "infinite" as equivalent to
844 :     * Long.MAX_VALUE. For splits, it uses the standard divide-by-two
845 :     * approach. The long and double versions of this class are
846 :     * identical except for types.
847 :     */
848 :     static class RandomIntsSpliterator implements Spliterator.OfInt {
849 :     final SplittableRandom rng;
850 :     long index;
851 :     final long fence;
852 :     final int origin;
853 :     final int bound;
854 :     RandomIntsSpliterator(SplittableRandom rng, long index, long fence,
855 :     int origin, int bound) {
856 :     this.rng = rng; this.index = index; this.fence = fence;
857 :     this.origin = origin; this.bound = bound;
858 :     }
859 :    
860 :     public RandomIntsSpliterator trySplit() {
861 :     long i = index, m = (i + fence) >>> 1;
862 :     return (m <= i) ? null :
863 :     new RandomIntsSpliterator(rng.split(), i, index = m, origin, bound);
864 :     }
865 :    
866 :     public long estimateSize() {
867 :     return fence - index;
868 :     }
869 :    
870 :     public int characteristics() {
871 :     return (Spliterator.SIZED | Spliterator.SUBSIZED |
872 :     Spliterator.ORDERED | Spliterator.NONNULL |
873 :     Spliterator.IMMUTABLE);
874 :     }
875 :    
876 :     public boolean tryAdvance(IntConsumer consumer) {
877 :     if (consumer == null) throw new NullPointerException();
878 :     long i = index, f = fence;
879 :     if (i < f) {
880 :     consumer.accept(rng.internalNextInt(origin, bound));
881 :     index = i + 1;
882 :     return true;
883 :     }
884 :     return false;
885 :     }
886 :    
887 :     public void forEachRemaining(IntConsumer consumer) {
888 :     if (consumer == null) throw new NullPointerException();
889 :     long i = index, f = fence;
890 :     if (i < f) {
891 :     index = f;
892 :     int o = origin, b = bound;
893 :     do {
894 :     consumer.accept(rng.internalNextInt(o, b));
895 :     } while (++i < f);
896 :     }
897 :     }
898 :     }
899 :    
900 :     /**
901 :     * Spliterator for long streams.
902 :     */
903 :     static class RandomLongsSpliterator implements Spliterator.OfLong {
904 :     final SplittableRandom rng;
905 :     long index;
906 :     final long fence;
907 :     final long origin;
908 :     final long bound;
909 :     RandomLongsSpliterator(SplittableRandom rng, long index, long fence,
910 :     long origin, long bound) {
911 :     this.rng = rng; this.index = index; this.fence = fence;
912 :     this.origin = origin; this.bound = bound;
913 :     }
914 :    
915 :     public RandomLongsSpliterator trySplit() {
916 :     long i = index, m = (i + fence) >>> 1;
917 :     return (m <= i) ? null :
918 :     new RandomLongsSpliterator(rng.split(), i, index = m, origin, bound);
919 :     }
920 :    
921 :     public long estimateSize() {
922 :     return fence - index;
923 :     }
924 :    
925 :     public int characteristics() {
926 :     return (Spliterator.SIZED | Spliterator.SUBSIZED |
927 :     Spliterator.ORDERED | Spliterator.NONNULL |
928 :     Spliterator.IMMUTABLE);
929 :     }
930 :    
931 :     public boolean tryAdvance(LongConsumer consumer) {
932 :     if (consumer == null) throw new NullPointerException();
933 :     long i = index, f = fence;
934 :     if (i < f) {
935 :     consumer.accept(rng.internalNextLong(origin, bound));
936 :     index = i + 1;
937 :     return true;
938 :     }
939 :     return false;
940 :     }
941 :    
942 :     public void forEachRemaining(LongConsumer consumer) {
943 :     if (consumer == null) throw new NullPointerException();
944 :     long i = index, f = fence;
945 :     if (i < f) {
946 :     index = f;
947 :     long o = origin, b = bound;
948 :     do {
949 :     consumer.accept(rng.internalNextLong(o, b));
950 :     } while (++i < f);
951 :     }
952 :     }
953 :    
954 :     }
955 :    
956 :     /**
957 :     * Spliterator for double streams.
958 :     */
959 :     static class RandomDoublesSpliterator implements Spliterator.OfDouble {
960 :     final SplittableRandom rng;
961 :     long index;
962 :     final long fence;
963 :     final double origin;
964 :     final double bound;
965 :     RandomDoublesSpliterator(SplittableRandom rng, long index, long fence,
966 :     double origin, double bound) {
967 :     this.rng = rng; this.index = index; this.fence = fence;
968 :     this.origin = origin; this.bound = bound;
969 :     }
970 :    
971 :     public RandomDoublesSpliterator trySplit() {
972 :     long i = index, m = (i + fence) >>> 1;
973 :     return (m <= i) ? null :
974 :     new RandomDoublesSpliterator(rng.split(), i, index = m, origin, bound);
975 :     }
976 :    
977 :     public long estimateSize() {
978 :     return fence - index;
979 :     }
980 :    
981 :     public int characteristics() {
982 :     return (Spliterator.SIZED | Spliterator.SUBSIZED |
983 :     Spliterator.ORDERED | Spliterator.NONNULL |
984 :     Spliterator.IMMUTABLE);
985 :     }
986 :    
987 :     public boolean tryAdvance(DoubleConsumer consumer) {
988 :     if (consumer == null) throw new NullPointerException();
989 :     long i = index, f = fence;
990 :     if (i < f) {
991 :     consumer.accept(rng.internalNextDouble(origin, bound));
992 :     index = i + 1;
993 :     return true;
994 :     }
995 :     return false;
996 :     }
997 :    
998 :     public void forEachRemaining(DoubleConsumer consumer) {
999 :     if (consumer == null) throw new NullPointerException();
1000 :     long i = index, f = fence;
1001 :     if (i < f) {
1002 :     index = f;
1003 :     double o = origin, b = bound;
1004 :     do {
1005 :     consumer.accept(rng.internalNextDouble(o, b));
1006 :     } while (++i < f);
1007 :     }
1008 :     }
1009 :     }
1010 :    
1011 :     }
1012 :    

Doug Lea
ViewVC Help
Powered by ViewVC 1.0.8