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

Doug Lea
ViewVC Help
Powered by ViewVC 1.0.8