ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/SplittableRandom.java
(Generate patch)

Comparing jsr166/src/main/java/util/SplittableRandom.java (file contents):
Revision 1.7 by dl, Fri Jul 12 11:26:34 2013 UTC vs.
Revision 1.20 by jsr166, Sat Aug 24 06:20:15 2013 UTC

# Line 25 | Line 25
25  
26   package java.util;
27  
28 + import java.security.SecureRandom;
29 + import java.net.InetAddress;
30   import java.util.concurrent.atomic.AtomicLong;
29 import java.util.Spliterator;
31   import java.util.function.IntConsumer;
32   import java.util.function.LongConsumer;
33   import java.util.function.DoubleConsumer;
# Line 38 | Line 39 | import java.util.stream.DoubleStream;
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
42 > * generate subtasks. Class {@code SplittableRandom} supports methods for
43   * producing pseudorandom numbers of type {@code int}, {@code long},
44   * and {@code double} with similar usages as for class
45 < * {@link java.util.Random} but differs in the following ways: <ul>
45 > * {@link java.util.Random} but differs in the following ways:
46 > *
47 > * <ul>
48   *
49   * <li>Series of generated values pass the DieHarder suite testing
50   * independence and uniformity properties of random number generators.
# Line 49 | Line 52 | import java.util.stream.DoubleStream;
52   * href="http://www.phy.duke.edu/~rgb/General/dieharder.php"> version
53   * 3.31.1</a>.) These tests validate only the methods for certain
54   * types and ranges, but similar properties are expected to hold, at
55 < * least approximately, for others as well.  </li>
55 > * least approximately, for others as well. The <em>period</em>
56 > * (length of any series of generated values before it repeats) is at
57 > * least 2<sup>64</sup>. </li>
58   *
59   * <li> Method {@link #split} constructs and returns a new
60   * SplittableRandom instance that shares no mutable state with the
# Line 72 | Line 77 | import java.util.stream.DoubleStream;
77   *
78   * </ul>
79   *
80 + * <p>Instances of {@code SplittableRandom} are not cryptographically
81 + * secure.  Consider instead using {@link java.security.SecureRandom}
82 + * in security-sensitive applications. Additionally,
83 + * default-constructed instances do not use a cryptographically random
84 + * seed unless the {@linkplain System#getProperty system property}
85 + * {@code java.util.secureRandomSeed} is set to {@code true}.
86 + *
87   * @author  Guy Steele
88   * @author  Doug Lea
89   * @since   1.8
# Line 79 | Line 91 | import java.util.stream.DoubleStream;
91   public class SplittableRandom {
92  
93      /*
82     * File organization: First the non-public methods that constitute
83     * the main algorithm, then the main public methods, followed by
84     * some custom spliterator classes needed for stream methods.
85     *
86     * Credits: Primary algorithm and code by Guy Steele.  Stream
87     * support methods by Doug Lea.  Documentation jointly produced
88     * with additional help from Brian Goetz.
89     */
90
91    /*
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 <     * 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 <     *
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.
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 <     * not calls to nextSeed(): Each instance carries the state of
117 <     * 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
99 >     * PPoPP 2012, as well as those in "Parallel random numbers: as
100 >     * easy as 1, 2, 3" by Salmon, Morae, Dror, and Shaw, SC 2011.  It
101 >     * differs mainly in simplifying and cheapening operations.
102 >     *
103 >     * The primary update step (method nextSeed()) is to add a
104 >     * constant ("gamma") to the current (64 bit) seed, forming a
105 >     * simple sequence.  The seed and the gamma values for any two
106 >     * SplittableRandom instances are highly likely to be different.
107 >     *
108 >     * Methods nextLong, nextInt, and derivatives do not return the
109 >     * sequence (seed) values, but instead a hash-like bit-mix of
110 >     * their bits, producing more independently distributed sequences.
111 >     * For nextLong, the mix64 bit-mixing function computes the same
112 >     * value as the "64-bit finalizer" function in Austin Appleby's
113 >     * MurmurHash3 algorithm.  See
114       * http://code.google.com/p/smhasher/wiki/MurmurHash3 , which
115       * comments: "The constants for the finalizers were generated by a
116       * simple simulated-annealing algorithm, and both avalanche all
117 <     * bits of 'h' to within 0.25% bias." It also appears to work to
118 <     * use instead any of the variants proposed by David Stafford at
119 <     * http://zimbry.blogspot.com/2011/09/better-bit-mixing-improving-on.html
120 <     * but these variants have not yet been tested as thoroughly
121 <     * in the context of the implementation of SplittableRandom.
122 <     *
123 <     * The mix32 function used for nextInt just consists of two of the
124 <     * five lines of mix64; avalanche testing shows that the 64-bit result
125 <     * has its top 32 bits avalanched well, though not the bottom 32 bits.
126 <     * DieHarder tests show that it is adequate for generating one
127 <     * random int from the 64-bit result of nextSeed.
128 <     *
129 <     * Support for the default (no-argument) constructor relies on an
130 <     * AtomicLong (defaultSeedGenerator) to help perform the
131 <     * equivalent of a split of a statically constructed
132 <     * SplittableRandom. Unlike other cases, this split must be
133 <     * performed in a thread-safe manner. We use
134 <     * AtomicLong.compareAndSet as the (typically) most efficient
135 <     * mechanism. To bootstrap, we start off using System.nanotime(),
136 <     * and update using another "genuinely random" constant
137 <     * DEFAULT_SEED_GAMMA. The default constructor uses GAMMA_GAMMA,
138 <     * not 0, for its splitSeed argument (addGammaModGeorge(0,
139 <     * GAMMA_GAMMA) == GAMMA_GAMMA) to reflect that each is split from
140 <     * this root generator, even though the root is not explicitly
141 <     * represented as a SplittableRandom.
117 >     * bits of 'h' to within 0.25% bias." The mix32 function is
118 >     * equivalent to (int)(mix64(seed) >>> 32), but faster because it
119 >     * omits a step that doesn't contribute to result.
120 >     *
121 >     * The split operation uses the current generator to form the seed
122 >     * and gamma for another SplittableRandom.  To conservatively
123 >     * avoid potential correlations between seed and value generation,
124 >     * gamma selection (method nextGamma) uses the "Mix13" constants
125 >     * for MurmurHash3 described by David Stafford
126 >     * (http://zimbry.blogspot.com/2011/09/better-bit-mixing-improving-on.html)
127 >     * To avoid potential weaknesses in bit-mixing transformations, we
128 >     * restrict gammas to odd values with at least 12 and no more than
129 >     * 52 bits set.  Rather than rejecting candidates with too few or
130 >     * too many bits set, method nextGamma flips some bits (which has
131 >     * the effect of mapping at most 4 to any given gamma value).
132 >     * This reduces the effective set of 64bit odd gamma values by
133 >     * about 2<sup>14</sup>, a very tiny percentage, and serves as an
134 >     * automated screening for sequence constant selection that is
135 >     * left as an empirical decision in some other hashing and crypto
136 >     * algorithms.
137 >     *
138 >     * The resulting generator thus transforms a sequence in which
139 >     * (typically) many bits change on each step, with an inexpensive
140 >     * mixer with good (but less than cryptographically secure)
141 >     * avalanching.
142 >     *
143 >     * The default (no-argument) constructor, in essence, invokes
144 >     * split() for a common "seeder" SplittableRandom.  Unlike other
145 >     * cases, this split must be performed in a thread-safe manner, so
146 >     * we use an AtomicLong to represent the seed rather than use an
147 >     * explicit SplittableRandom. To bootstrap the seeder, we start
148 >     * off using a seed based on current time and host unless the
149 >     * java.util.secureRandomSeed property is set. This serves as a
150 >     * slimmed-down (and insecure) variant of SecureRandom that also
151 >     * avoids stalls that may occur when using /dev/random.
152 >     *
153 >     * It is a relatively simple matter to apply the basic design here
154 >     * to use 128 bit seeds. However, emulating 128bit arithmetic and
155 >     * carrying around twice the state add more overhead than appears
156 >     * warranted for current usages.
157 >     *
158 >     * File organization: First the non-public methods that constitute
159 >     * the main algorithm, then the main public methods, followed by
160 >     * some custom spliterator classes needed for stream methods.
161       */
162  
163      /**
164 <     * The "genuinely random" value for producing new gamma values.
165 <     * The value is arbitrary, subject to the requirement that it be
166 <     * 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.
164 >     * The initial gamma value for (unsplit) SplittableRandoms. Must
165 >     * be odd with at least 12 and no more than 52 bits set. Currently
166 >     * set to the golden ratio scaled to 64bits.
167       */
168 <    private static final long DEFAULT_SEED_GAMMA = 0xBD24B73A95FB84D9L;
168 >    private static final long INITIAL_GAMMA = 0x9e3779b97f4a7c15L;
169  
170      /**
171       * The least non-zero value returned by nextDouble(). This value
# Line 184 | Line 174 | public class SplittableRandom {
174      private static final double DOUBLE_UNIT = 1.0 / (1L << 53);
175  
176      /**
177 <     * The next seed for default constructors.
188 <     */
189 <    private static final AtomicLong defaultSeedGenerator =
190 <        new AtomicLong(System.nanoTime());
191 <
192 <    /**
193 <     * The seed, updated only via method nextSeed.
177 >     * The seed. Updated only via method nextSeed.
178       */
179      private long seed;
180  
181      /**
182 <     * The constant value added to seed (mod George) on each update.
182 >     * The step value.
183       */
184      private final long gamma;
185  
186      /**
187 <     * The next seed to use for splits. Propagated using
204 <     * addGammaModGeorge across instances.
187 >     * Internal constructor used by all others except default constructor.
188       */
189 <    private final long nextSplit;
190 <
191 <    /**
209 <     * Adds the given gamma value, g, to the given seed value s, mod
210 <     * George (2^64+13). We regard s and g as unsigned values
211 <     * (ranging from 0 to 2^64-1). We add g to s either once or twice
212 <     * (mod George) as necessary to produce an (unsigned) result less
213 <     * than 2^64.  We require that g must be at least 13. This
214 <     * guarantees that if (s+g) mod George >= 2^64 then (s+g+g) mod
215 <     * George < 2^64; thus we need only a conditional, not a loop,
216 <     * to be sure of getting a representable value.
217 <     *
218 <     * @param s a seed value
219 <     * @param g a gamma value, 13 <= g (as unsigned)
220 <     */
221 <    private static long addGammaModGeorge(long s, long g) {
222 <        long p = s + g;
223 <        if (Long.compareUnsigned(p, g) >= 0)
224 <            return p;
225 <        long q = p - 13L;
226 <        return (Long.compareUnsigned(p, 13L) >= 0) ? q : (q + g);
189 >    private SplittableRandom(long seed, long gamma) {
190 >        this.seed = seed;
191 >        this.gamma = gamma;
192      }
193  
194      /**
195 <     * Returns a bit-mixed transformation of its argument.
231 <     * See above for explanation.
195 >     * Computes MurmurHash3 64bit mix function.
196       */
197      private static long mix64(long z) {
198 <        z ^= (z >>> 33);
199 <        z *= 0xff51afd7ed558ccdL;
200 <        z ^= (z >>> 33);
237 <        z *= 0xc4ceb9fe1a85ec53L;
238 <        z ^= (z >>> 33);
239 <        return z;
198 >        z = (z ^ (z >>> 33)) * 0xff51afd7ed558ccdL;
199 >        z = (z ^ (z >>> 33)) * 0xc4ceb9fe1a85ec53L;
200 >        return z ^ (z >>> 33);
201      }
202  
203      /**
204 <     * Returns a bit-mixed int transformation of its argument.
244 <     * See above for explanation.
204 >     * Returns the 32 high bits of mix64(z) as int.
205       */
206      private static int mix32(long z) {
207 <        z ^= (z >>> 33);
208 <        z *= 0xc4ceb9fe1a85ec53L;
249 <        return (int)(z >>> 32);
207 >        z = (z ^ (z >>> 33)) * 0xff51afd7ed558ccdL;
208 >        return (int)(((z ^ (z >>> 33)) * 0xc4ceb9fe1a85ec53L) >>> 32);
209      }
210  
211      /**
212 <     * Internal constructor used by all other constructors and by
254 <     * method split. Establishes the initial seed for this instance,
255 <     * and uses the given splitSeed to establish gamma, as well as the
256 <     * nextSplit to use by this instance. The loop to skip ineligible
257 <     * gammas very rarely iterates, and does so at most 13 times.
212 >     * Returns the gamma value to use for a new split instance.
213       */
214 <    private SplittableRandom(long seed, long splitSeed) {
215 <        this.seed = seed;
216 <        long s = splitSeed, g;
217 <        do { // ensure gamma >= 13, considered as an unsigned integer
218 <            s = addGammaModGeorge(s, GAMMA_GAMMA);
219 <            g = mix64(s);
265 <        } while (Long.compareUnsigned(g, 13L) < 0);
266 <        this.gamma = g;
267 <        this.nextSplit = s;
214 >    private static long nextGamma(long z) {
215 >        z = (z ^ (z >>> 30)) * 0xbf58476d1ce4e5b9L; // Stafford "Mix13"
216 >        z = (z ^ (z >>> 27)) * 0x94d049bb133111ebL;
217 >        z = (z ^ (z >>> 31)) | 1L; // force to be odd
218 >        int n = Long.bitCount(z);  // ensure enough 0 and 1 bits
219 >        return (n < 12 || n > 52) ? z ^ 0xaaaaaaaaaaaaaaaaL : z;
220      }
221  
222      /**
223 <     * Updates in-place and returns seed.
272 <     * See above for explanation.
223 >     * Adds gamma to seed.
224       */
225      private long nextSeed() {
226 <        return seed = addGammaModGeorge(seed, gamma);
226 >        return seed += gamma;
227      }
228  
229      /**
230 <     * Atomically updates and returns next seed for default constructor.
230 >     * The seed generator for default constructors.
231       */
232 <    private static long nextDefaultSeed() {
233 <        long oldSeed, newSeed;
234 <        do {
235 <            oldSeed = defaultSeedGenerator.get();
236 <            newSeed = addGammaModGeorge(oldSeed, DEFAULT_SEED_GAMMA);
237 <        } while (!defaultSeedGenerator.compareAndSet(oldSeed, newSeed));
238 <        return mix64(newSeed);
232 >    private static final AtomicLong seeder = new AtomicLong(initialSeed());
233 >
234 >    private static long initialSeed() {
235 >        try {  // ignore exceptions in accessing/parsing properties
236 >            String pp = System.getProperty
237 >                ("java.util.secureRandomSeed");
238 >            if (pp != null && pp.equalsIgnoreCase("true")) {
239 >                byte[] seedBytes = java.security.SecureRandom.getSeed(8);
240 >                long s = (long)(seedBytes[0]) & 0xffL;
241 >                for (int i = 1; i < 8; ++i)
242 >                    s = (s << 8) | ((long)(seedBytes[i]) & 0xffL);
243 >                return s;
244 >            }
245 >        } catch (Exception ignore) {
246 >        }
247 >        int hh = 0; // hashed host address
248 >        try {
249 >            hh = InetAddress.getLocalHost().hashCode();
250 >        } catch (Exception ignore) {
251 >        }
252 >        return (mix64((((long)hh) << 32) ^ System.currentTimeMillis()) ^
253 >                mix64(System.nanoTime()));
254      }
255  
256 +    // IllegalArgumentException messages
257 +    static final String BadBound = "bound must be positive";
258 +    static final String BadRange = "bound must be greater than origin";
259 +    static final String BadSize  = "size must be non-negative";
260 +
261      /*
262       * Internal versions of nextX methods used by streams, as well as
263       * the public nextX(origin, bound) methods.  These exist mainly to
# Line 362 | Line 333 | public class SplittableRandom {
333          int r = mix32(nextSeed());
334          if (origin < bound) {
335              int n = bound - origin, m = n - 1;
336 <            if ((n & m) == 0L)
336 >            if ((n & m) == 0)
337                  r = (r & m) + origin;
338              else if (n > 0) {
339                  for (int u = r >>> 1;
# Line 401 | Line 372 | public class SplittableRandom {
372      /**
373       * Creates a new SplittableRandom instance using the specified
374       * initial seed. SplittableRandom instances created with the same
375 <     * seed generate identical sequences of values.
375 >     * seed in the same program generate identical sequences of values.
376       *
377       * @param seed the initial seed
378       */
379      public SplittableRandom(long seed) {
380 <        this(seed, 0);
380 >        this(seed, INITIAL_GAMMA);
381      }
382  
383      /**
# Line 415 | Line 386 | public class SplittableRandom {
386       * of those of any other instances in the current program; and
387       * may, and typically does, vary across program invocations.
388       */
389 <    public SplittableRandom() {
390 <        this(nextDefaultSeed(), GAMMA_GAMMA);
389 >    public SplittableRandom() { // emulate seeder.split()
390 >        this.gamma = nextGamma(this.seed = seeder.addAndGet(INITIAL_GAMMA));
391      }
392  
393      /**
# Line 434 | Line 405 | public class SplittableRandom {
405       * @return the new SplittableRandom instance
406       */
407      public SplittableRandom split() {
408 <        return new SplittableRandom(nextSeed(), nextSplit);
408 >        long s = nextSeed();
409 >        return new SplittableRandom(s, nextGamma(s));
410      }
411  
412      /**
# Line 450 | Line 422 | public class SplittableRandom {
422       * Returns a pseudorandom {@code int} value between zero (inclusive)
423       * and the specified bound (exclusive).
424       *
425 <     * @param bound the bound on the random number to be returned.  Must be
454 <     *        positive.
425 >     * @param bound the upper bound (exclusive).  Must be positive.
426       * @return a pseudorandom {@code int} value between zero
427 <     *         (inclusive) and the bound (exclusive).
428 <     * @throws IllegalArgumentException if the bound is less than zero
427 >     *         (inclusive) and the bound (exclusive)
428 >     * @throws IllegalArgumentException if {@code bound} is not positive
429       */
430      public int nextInt(int bound) {
431          if (bound <= 0)
432 <            throw new IllegalArgumentException("bound must be positive");
432 >            throw new IllegalArgumentException(BadBound);
433          // Specialize internalNextInt for origin 0
434          int r = mix32(nextSeed());
435          int m = bound - 1;
436 <        if ((bound & m) == 0L) // power of two
436 >        if ((bound & m) == 0) // power of two
437              r &= m;
438          else { // reject over-represented candidates
439              for (int u = r >>> 1;
# Line 480 | Line 451 | public class SplittableRandom {
451       * @param origin the least value returned
452       * @param bound the upper bound (exclusive)
453       * @return a pseudorandom {@code int} value between the origin
454 <     *         (inclusive) and the bound (exclusive).
454 >     *         (inclusive) and the bound (exclusive)
455       * @throws IllegalArgumentException if {@code origin} is greater than
456       *         or equal to {@code bound}
457       */
458      public int nextInt(int origin, int bound) {
459          if (origin >= bound)
460 <            throw new IllegalArgumentException("bound must be greater than origin");
460 >            throw new IllegalArgumentException(BadRange);
461          return internalNextInt(origin, bound);
462      }
463  
# Line 503 | Line 474 | public class SplittableRandom {
474       * Returns a pseudorandom {@code long} value between zero (inclusive)
475       * and the specified bound (exclusive).
476       *
477 <     * @param bound the bound on the random number to be returned.  Must be
507 <     *        positive.
477 >     * @param bound the upper bound (exclusive).  Must be positive.
478       * @return a pseudorandom {@code long} value between zero
479 <     *         (inclusive) and the bound (exclusive).
480 <     * @throws IllegalArgumentException if {@code bound} is less than zero
479 >     *         (inclusive) and the bound (exclusive)
480 >     * @throws IllegalArgumentException if {@code bound} is not positive
481       */
482      public long nextLong(long bound) {
483          if (bound <= 0)
484 <            throw new IllegalArgumentException("bound must be positive");
484 >            throw new IllegalArgumentException(BadBound);
485          // Specialize internalNextLong for origin 0
486          long r = mix64(nextSeed());
487          long m = bound - 1;
# Line 533 | Line 503 | public class SplittableRandom {
503       * @param origin the least value returned
504       * @param bound the upper bound (exclusive)
505       * @return a pseudorandom {@code long} value between the origin
506 <     *         (inclusive) and the bound (exclusive).
506 >     *         (inclusive) and the bound (exclusive)
507       * @throws IllegalArgumentException if {@code origin} is greater than
508       *         or equal to {@code bound}
509       */
510      public long nextLong(long origin, long bound) {
511          if (origin >= bound)
512 <            throw new IllegalArgumentException("bound must be greater than origin");
512 >            throw new IllegalArgumentException(BadRange);
513          return internalNextLong(origin, bound);
514      }
515  
# Line 548 | Line 518 | public class SplittableRandom {
518       * (inclusive) and one (exclusive).
519       *
520       * @return a pseudorandom {@code double} value between zero
521 <     * (inclusive) and one (exclusive)
521 >     *         (inclusive) and one (exclusive)
522       */
523      public double nextDouble() {
524 <        return (nextLong() >>> 11) * DOUBLE_UNIT;
524 >        return (mix64(nextSeed()) >>> 11) * DOUBLE_UNIT;
525      }
526  
527      /**
528       * Returns a pseudorandom {@code double} value between 0.0
529       * (inclusive) and the specified bound (exclusive).
530       *
531 <     * @param bound the bound on the random number to be returned.  Must be
562 <     *        positive.
531 >     * @param bound the upper bound (exclusive).  Must be positive.
532       * @return a pseudorandom {@code double} value between zero
533 <     *         (inclusive) and the bound (exclusive).
534 <     * @throws IllegalArgumentException if {@code bound} is less than zero
533 >     *         (inclusive) and the bound (exclusive)
534 >     * @throws IllegalArgumentException if {@code bound} is not positive
535       */
536      public double nextDouble(double bound) {
537          if (!(bound > 0.0))
538 <            throw new IllegalArgumentException("bound must be positive");
539 <        double result = nextDouble() * bound;
538 >            throw new IllegalArgumentException(BadBound);
539 >        double result = (mix64(nextSeed()) >>> 11) * DOUBLE_UNIT * bound;
540          return (result < bound) ?  result : // correct for rounding
541              Double.longBitsToDouble(Double.doubleToLongBits(bound) - 1);
542      }
# Line 577 | Line 546 | public class SplittableRandom {
546       * origin (inclusive) and bound (exclusive).
547       *
548       * @param origin the least value returned
549 <     * @param bound the upper bound
549 >     * @param bound the upper bound (exclusive)
550       * @return a pseudorandom {@code double} value between the origin
551 <     *         (inclusive) and the bound (exclusive).
551 >     *         (inclusive) and the bound (exclusive)
552       * @throws IllegalArgumentException if {@code origin} is greater than
553       *         or equal to {@code bound}
554       */
555      public double nextDouble(double origin, double bound) {
556          if (!(origin < bound))
557 <            throw new IllegalArgumentException("bound must be greater than origin");
557 >            throw new IllegalArgumentException(BadRange);
558          return internalNextDouble(origin, bound);
559      }
560  
561 +    /**
562 +     * Returns a pseudorandom {@code boolean} value.
563 +     *
564 +     * @return a pseudorandom {@code boolean} value
565 +     */
566 +    public boolean nextBoolean() {
567 +        return mix32(nextSeed()) < 0;
568 +    }
569 +
570      // stream methods, coded in a way intended to better isolate for
571      // maintenance purposes the small differences across forms.
572  
573      /**
574 <     * Returns a stream producing the given {@code streamSize} number of
575 <     * pseudorandom {@code int} values.
574 >     * Returns a stream producing the given {@code streamSize} number
575 >     * of pseudorandom {@code int} values from this generator and/or
576 >     * one split from it.
577       *
578       * @param streamSize the number of values to generate
579       * @return a stream of pseudorandom {@code int} values
# Line 603 | Line 582 | public class SplittableRandom {
582       */
583      public IntStream ints(long streamSize) {
584          if (streamSize < 0L)
585 <            throw new IllegalArgumentException("negative Stream size");
585 >            throw new IllegalArgumentException(BadSize);
586          return StreamSupport.intStream
587              (new RandomIntsSpliterator
588               (this, 0L, streamSize, Integer.MAX_VALUE, 0),
# Line 612 | Line 591 | public class SplittableRandom {
591  
592      /**
593       * Returns an effectively unlimited stream of pseudorandom {@code int}
594 <     * values
594 >     * values from this generator and/or one split from it.
595       *
596       * @implNote This method is implemented to be equivalent to {@code
597       * ints(Long.MAX_VALUE)}.
# Line 627 | Line 606 | public class SplittableRandom {
606      }
607  
608      /**
609 <     * Returns a stream producing the given {@code streamSize} number of
610 <     * pseudorandom {@code int} values, each conforming to the given
611 <     * origin and bound.
609 >     * Returns a stream producing the given {@code streamSize} number
610 >     * of pseudorandom {@code int} values from this generator and/or one split
611 >     * from it; each value conforms to the given origin (inclusive) and bound
612 >     * (exclusive).
613       *
614       * @param streamSize the number of values to generate
615 <     * @param randomNumberOrigin the origin of each random value
616 <     * @param randomNumberBound the bound of each random value
615 >     * @param randomNumberOrigin the origin (inclusive) of each random value
616 >     * @param randomNumberBound the bound (exclusive) of each random value
617       * @return a stream of pseudorandom {@code int} values,
618 <     *         each with the given origin and bound.
618 >     *         each with the given origin (inclusive) and bound (exclusive)
619       * @throws IllegalArgumentException if {@code streamSize} is
620       *         less than zero, or {@code randomNumberOrigin}
621       *         is greater than or equal to {@code randomNumberBound}
# Line 643 | Line 623 | public class SplittableRandom {
623      public IntStream ints(long streamSize, int randomNumberOrigin,
624                            int randomNumberBound) {
625          if (streamSize < 0L)
626 <            throw new IllegalArgumentException("negative Stream size");
626 >            throw new IllegalArgumentException(BadSize);
627          if (randomNumberOrigin >= randomNumberBound)
628 <            throw new IllegalArgumentException("bound must be greater than origin");
628 >            throw new IllegalArgumentException(BadRange);
629          return StreamSupport.intStream
630              (new RandomIntsSpliterator
631               (this, 0L, streamSize, randomNumberOrigin, randomNumberBound),
# Line 654 | Line 634 | public class SplittableRandom {
634  
635      /**
636       * Returns an effectively unlimited stream of pseudorandom {@code
637 <     * int} values, each conforming to the given origin and bound.
637 >     * int} values from this generator and/or one split from it; each value
638 >     * conforms to the given origin (inclusive) and bound (exclusive).
639       *
640       * @implNote This method is implemented to be equivalent to {@code
641       * ints(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
642       *
643 <     * @param randomNumberOrigin the origin of each random value
644 <     * @param randomNumberBound the bound of each random value
643 >     * @param randomNumberOrigin the origin (inclusive) of each random value
644 >     * @param randomNumberBound the bound (exclusive) of each random value
645       * @return a stream of pseudorandom {@code int} values,
646 <     *         each with the given origin and bound.
646 >     *         each with the given origin (inclusive) and bound (exclusive)
647       * @throws IllegalArgumentException if {@code randomNumberOrigin}
648       *         is greater than or equal to {@code randomNumberBound}
649       */
650      public IntStream ints(int randomNumberOrigin, int randomNumberBound) {
651          if (randomNumberOrigin >= randomNumberBound)
652 <            throw new IllegalArgumentException("bound must be greater than origin");
652 >            throw new IllegalArgumentException(BadRange);
653          return StreamSupport.intStream
654              (new RandomIntsSpliterator
655               (this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
# Line 676 | Line 657 | public class SplittableRandom {
657      }
658  
659      /**
660 <     * Returns a stream producing the given {@code streamSize} number of
661 <     * pseudorandom {@code long} values.
660 >     * Returns a stream producing the given {@code streamSize} number
661 >     * of pseudorandom {@code long} values from this generator and/or
662 >     * one split from it.
663       *
664       * @param streamSize the number of values to generate
665       * @return a stream of pseudorandom {@code long} values
# Line 686 | Line 668 | public class SplittableRandom {
668       */
669      public LongStream longs(long streamSize) {
670          if (streamSize < 0L)
671 <            throw new IllegalArgumentException("negative Stream size");
671 >            throw new IllegalArgumentException(BadSize);
672          return StreamSupport.longStream
673              (new RandomLongsSpliterator
674               (this, 0L, streamSize, Long.MAX_VALUE, 0L),
# Line 694 | Line 676 | public class SplittableRandom {
676      }
677  
678      /**
679 <     * Returns an effectively unlimited stream of pseudorandom {@code long}
680 <     * values.
679 >     * Returns an effectively unlimited stream of pseudorandom {@code
680 >     * long} values from this generator and/or one split from it.
681       *
682       * @implNote This method is implemented to be equivalent to {@code
683       * longs(Long.MAX_VALUE)}.
# Line 711 | Line 693 | public class SplittableRandom {
693  
694      /**
695       * Returns a stream producing the given {@code streamSize} number of
696 <     * pseudorandom {@code long} values, each conforming to the
697 <     * given origin and bound.
696 >     * pseudorandom {@code long} values from this generator and/or one split
697 >     * from it; each value conforms to the given origin (inclusive) and bound
698 >     * (exclusive).
699       *
700       * @param streamSize the number of values to generate
701 <     * @param randomNumberOrigin the origin of each random value
702 <     * @param randomNumberBound the bound of each random value
701 >     * @param randomNumberOrigin the origin (inclusive) of each random value
702 >     * @param randomNumberBound the bound (exclusive) of each random value
703       * @return a stream of pseudorandom {@code long} values,
704 <     *         each with the given origin and bound.
704 >     *         each with the given origin (inclusive) and bound (exclusive)
705       * @throws IllegalArgumentException if {@code streamSize} is
706       *         less than zero, or {@code randomNumberOrigin}
707       *         is greater than or equal to {@code randomNumberBound}
# Line 726 | Line 709 | public class SplittableRandom {
709      public LongStream longs(long streamSize, long randomNumberOrigin,
710                              long randomNumberBound) {
711          if (streamSize < 0L)
712 <            throw new IllegalArgumentException("negative Stream size");
712 >            throw new IllegalArgumentException(BadSize);
713          if (randomNumberOrigin >= randomNumberBound)
714 <            throw new IllegalArgumentException("bound must be greater than origin");
714 >            throw new IllegalArgumentException(BadRange);
715          return StreamSupport.longStream
716              (new RandomLongsSpliterator
717               (this, 0L, streamSize, randomNumberOrigin, randomNumberBound),
# Line 737 | Line 720 | public class SplittableRandom {
720  
721      /**
722       * Returns an effectively unlimited stream of pseudorandom {@code
723 <     * long} values, each conforming to the given origin and bound.
723 >     * long} values from this generator and/or one split from it; each value
724 >     * conforms to the given origin (inclusive) and bound (exclusive).
725       *
726       * @implNote This method is implemented to be equivalent to {@code
727       * longs(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
728       *
729 <     * @param randomNumberOrigin the origin of each random value
730 <     * @param randomNumberBound the bound of each random value
729 >     * @param randomNumberOrigin the origin (inclusive) of each random value
730 >     * @param randomNumberBound the bound (exclusive) of each random value
731       * @return a stream of pseudorandom {@code long} values,
732 <     *         each with the given origin and bound.
732 >     *         each with the given origin (inclusive) and bound (exclusive)
733       * @throws IllegalArgumentException if {@code randomNumberOrigin}
734       *         is greater than or equal to {@code randomNumberBound}
735       */
736      public LongStream longs(long randomNumberOrigin, long randomNumberBound) {
737          if (randomNumberOrigin >= randomNumberBound)
738 <            throw new IllegalArgumentException("bound must be greater than origin");
738 >            throw new IllegalArgumentException(BadRange);
739          return StreamSupport.longStream
740              (new RandomLongsSpliterator
741               (this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
# Line 760 | Line 744 | public class SplittableRandom {
744  
745      /**
746       * Returns a stream producing the given {@code streamSize} number of
747 <     * pseudorandom {@code double} values, each between zero
748 <     * (inclusive) and one (exclusive).
747 >     * pseudorandom {@code double} values from this generator and/or one split
748 >     * from it; each value is between zero (inclusive) and one (exclusive).
749       *
750       * @param streamSize the number of values to generate
751       * @return a stream of {@code double} values
# Line 770 | Line 754 | public class SplittableRandom {
754       */
755      public DoubleStream doubles(long streamSize) {
756          if (streamSize < 0L)
757 <            throw new IllegalArgumentException("negative Stream size");
757 >            throw new IllegalArgumentException(BadSize);
758          return StreamSupport.doubleStream
759              (new RandomDoublesSpliterator
760               (this, 0L, streamSize, Double.MAX_VALUE, 0.0),
# Line 779 | Line 763 | public class SplittableRandom {
763  
764      /**
765       * Returns an effectively unlimited stream of pseudorandom {@code
766 <     * double} values, each between zero (inclusive) and one
767 <     * (exclusive).
766 >     * double} values from this generator and/or one split from it; each value
767 >     * is between zero (inclusive) and one (exclusive).
768       *
769       * @implNote This method is implemented to be equivalent to {@code
770       * doubles(Long.MAX_VALUE)}.
# Line 796 | Line 780 | public class SplittableRandom {
780  
781      /**
782       * Returns a stream producing the given {@code streamSize} number of
783 <     * pseudorandom {@code double} values, each conforming to the
784 <     * given origin and bound.
783 >     * pseudorandom {@code double} values from this generator and/or one split
784 >     * from it; each value conforms to the given origin (inclusive) and bound
785 >     * (exclusive).
786       *
787       * @param streamSize the number of values to generate
788 <     * @param randomNumberOrigin the origin of each random value
789 <     * @param randomNumberBound the bound of each random value
788 >     * @param randomNumberOrigin the origin (inclusive) of each random value
789 >     * @param randomNumberBound the bound (exclusive) of each random value
790       * @return a stream of pseudorandom {@code double} values,
791 <     * each with the given origin and bound.
791 >     *         each with the given origin (inclusive) and bound (exclusive)
792       * @throws IllegalArgumentException if {@code streamSize} is
793 <     * less than zero.
793 >     *         less than zero
794       * @throws IllegalArgumentException if {@code randomNumberOrigin}
795       *         is greater than or equal to {@code randomNumberBound}
796       */
797      public DoubleStream doubles(long streamSize, double randomNumberOrigin,
798                                  double randomNumberBound) {
799          if (streamSize < 0L)
800 <            throw new IllegalArgumentException("negative Stream size");
800 >            throw new IllegalArgumentException(BadSize);
801          if (!(randomNumberOrigin < randomNumberBound))
802 <            throw new IllegalArgumentException("bound must be greater than origin");
802 >            throw new IllegalArgumentException(BadRange);
803          return StreamSupport.doubleStream
804              (new RandomDoublesSpliterator
805               (this, 0L, streamSize, randomNumberOrigin, randomNumberBound),
# Line 823 | Line 808 | public class SplittableRandom {
808  
809      /**
810       * Returns an effectively unlimited stream of pseudorandom {@code
811 <     * double} values, each conforming to the given origin and bound.
811 >     * double} values from this generator and/or one split from it; each value
812 >     * conforms to the given origin (inclusive) and bound (exclusive).
813       *
814       * @implNote This method is implemented to be equivalent to {@code
815       * doubles(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
816       *
817 <     * @param randomNumberOrigin the origin of each random value
818 <     * @param randomNumberBound the bound of each random value
817 >     * @param randomNumberOrigin the origin (inclusive) of each random value
818 >     * @param randomNumberBound the bound (exclusive) of each random value
819       * @return a stream of pseudorandom {@code double} values,
820 <     * each with the given origin and bound.
820 >     *         each with the given origin (inclusive) and bound (exclusive)
821       * @throws IllegalArgumentException if {@code randomNumberOrigin}
822       *         is greater than or equal to {@code randomNumberBound}
823       */
824      public DoubleStream doubles(double randomNumberOrigin, double randomNumberBound) {
825          if (!(randomNumberOrigin < randomNumberBound))
826 <            throw new IllegalArgumentException("bound must be greater than origin");
826 >            throw new IllegalArgumentException(BadRange);
827          return StreamSupport.doubleStream
828              (new RandomDoublesSpliterator
829               (this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
# Line 852 | Line 838 | public class SplittableRandom {
838       * approach. The long and double versions of this class are
839       * identical except for types.
840       */
841 <    static class RandomIntsSpliterator implements Spliterator.OfInt {
841 >    static final class RandomIntsSpliterator implements Spliterator.OfInt {
842          final SplittableRandom rng;
843          long index;
844          final long fence;
# Line 895 | Line 881 | public class SplittableRandom {
881              long i = index, f = fence;
882              if (i < f) {
883                  index = f;
884 +                SplittableRandom r = rng;
885                  int o = origin, b = bound;
886                  do {
887 <                    consumer.accept(rng.internalNextInt(o, b));
887 >                    consumer.accept(r.internalNextInt(o, b));
888                  } while (++i < f);
889              }
890          }
# Line 906 | Line 893 | public class SplittableRandom {
893      /**
894       * Spliterator for long streams.
895       */
896 <    static class RandomLongsSpliterator implements Spliterator.OfLong {
896 >    static final class RandomLongsSpliterator implements Spliterator.OfLong {
897          final SplittableRandom rng;
898          long index;
899          final long fence;
# Line 949 | Line 936 | public class SplittableRandom {
936              long i = index, f = fence;
937              if (i < f) {
938                  index = f;
939 +                SplittableRandom r = rng;
940                  long o = origin, b = bound;
941                  do {
942 <                    consumer.accept(rng.internalNextLong(o, b));
942 >                    consumer.accept(r.internalNextLong(o, b));
943                  } while (++i < f);
944              }
945          }
# Line 961 | Line 949 | public class SplittableRandom {
949      /**
950       * Spliterator for double streams.
951       */
952 <    static class RandomDoublesSpliterator implements Spliterator.OfDouble {
952 >    static final class RandomDoublesSpliterator implements Spliterator.OfDouble {
953          final SplittableRandom rng;
954          long index;
955          final long fence;
# Line 1004 | Line 992 | public class SplittableRandom {
992              long i = index, f = fence;
993              if (i < f) {
994                  index = f;
995 +                SplittableRandom r = rng;
996                  double o = origin, b = bound;
997                  do {
998 <                    consumer.accept(rng.internalNextDouble(o, b));
998 >                    consumer.accept(r.internalNextDouble(o, b));
999                  } while (++i < f);
1000              }
1001          }
1002      }
1003  
1004   }
1016

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines