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

Doug Lea
ViewVC Help
Powered by ViewVC 1.0.8