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.10 by jsr166, Sun Jul 14 08:06:49 2013 UTC vs.
Revision 1.22 by dl, Fri Sep 20 09:38:07 2013 UTC

# Line 25 | Line 25
25  
26   package java.util;
27  
28 + import java.security.SecureRandom;
29 + import java.net.NetworkInterface;
30 + import java.util.Enumeration;
31   import java.util.concurrent.atomic.AtomicLong;
29 import java.util.Spliterator;
32   import java.util.function.IntConsumer;
33   import java.util.function.LongConsumer;
34   import java.util.function.DoubleConsumer;
# Line 38 | Line 40 | import java.util.stream.DoubleStream;
40   /**
41   * A generator of uniform pseudorandom values applicable for use in
42   * (among other contexts) isolated parallel computations that may
43 < * generate subtasks. Class SplittableRandom supports methods for
43 > * generate subtasks. Class {@code SplittableRandom} supports methods for
44   * producing pseudorandom numbers of type {@code int}, {@code long},
45   * and {@code double} with similar usages as for class
46   * {@link java.util.Random} but differs in the following ways:
# Line 51 | Line 53 | import java.util.stream.DoubleStream;
53   * href="http://www.phy.duke.edu/~rgb/General/dieharder.php"> version
54   * 3.31.1</a>.) These tests validate only the methods for certain
55   * types and ranges, but similar properties are expected to hold, at
56 < * least approximately, for others as well.  </li>
56 > * least approximately, for others as well. The <em>period</em>
57 > * (length of any series of generated values before it repeats) is at
58 > * least 2<sup>64</sup>. </li>
59   *
60   * <li> Method {@link #split} constructs and returns a new
61   * SplittableRandom instance that shares no mutable state with the
# Line 74 | Line 78 | import java.util.stream.DoubleStream;
78   *
79   * </ul>
80   *
81 + * <p>Instances of {@code SplittableRandom} are not cryptographically
82 + * secure.  Consider instead using {@link java.security.SecureRandom}
83 + * in security-sensitive applications. Additionally,
84 + * default-constructed instances do not use a cryptographically random
85 + * seed unless the {@linkplain System#getProperty system property}
86 + * {@code java.util.secureRandomSeed} is set to {@code true}.
87 + *
88   * @author  Guy Steele
89   * @author  Doug Lea
90   * @since   1.8
# Line 81 | Line 92 | import java.util.stream.DoubleStream;
92   public class SplittableRandom {
93  
94      /*
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    /*
95       * Implementation Overview.
96       *
97       * This algorithm was inspired by the "DotMix" algorithm by
98       * Leiserson, Schardl, and Sukha "Deterministic Parallel
99       * Random-Number Generation for Dynamic-Multithreading Platforms",
100 <     * PPoPP 2012, but improves and extends it in several ways.
100 >     * PPoPP 2012, as well as those in "Parallel random numbers: as
101 >     * easy as 1, 2, 3" by Salmon, Morae, Dror, and Shaw, SC 2011.  It
102 >     * differs mainly in simplifying and cheapening operations.
103 >     *
104 >     * The primary update step (method nextSeed()) is to add a
105 >     * constant ("gamma") to the current (64 bit) seed, forming a
106 >     * simple sequence.  The seed and the gamma values for any two
107 >     * SplittableRandom instances are highly likely to be different.
108 >     *
109 >     * Methods nextLong, nextInt, and derivatives do not return the
110 >     * sequence (seed) values, but instead a hash-like bit-mix of
111 >     * their bits, producing more independently distributed sequences.
112 >     * For nextLong, the mix64 function is based on David Stafford's
113 >     * (http://zimbry.blogspot.com/2011/09/better-bit-mixing-improving-on.html)
114 >     * "Mix13" variant of the "64-bit finalizer" function in Austin
115 >     * Appleby's MurmurHash3 algorithm See
116 >     * http://code.google.com/p/smhasher/wiki/MurmurHash3 . The mix32
117 >     * function is based on Stafford's Mix04 mix function, but returns
118 >     * the upper 32 bits cast as int.
119 >     *
120 >     * The split operation uses the current generator to form the seed
121 >     * and gamma for another SplittableRandom.  To conservatively
122 >     * avoid potential correlations between seed and value generation,
123 >     * gamma selection (method mixGamma) uses different
124 >     * (Murmurhash3's) mix constants.  To avoid potential weaknesses
125 >     * in bit-mixing transformations, we restrict gammas to odd values
126 >     * with at least 24 0-1 or 1-0 bit transitions.  Rather than
127 >     * rejecting candidates with too few or too many bits set, method
128 >     * mixGamma flips some bits (which has the effect of mapping at
129 >     * most 4 to any given gamma value).  This reduces the effective
130 >     * set of 64bit odd gamma values by about 2%, and serves as an
131 >     * automated screening for sequence constant selection that is
132 >     * left as an empirical decision in some other hashing and crypto
133 >     * algorithms.
134 >     *
135 >     * The resulting generator thus transforms a sequence in which
136 >     * (typically) many bits change on each step, with an inexpensive
137 >     * mixer with good (but less than cryptographically secure)
138 >     * avalanching.
139 >     *
140 >     * The default (no-argument) constructor, in essence, invokes
141 >     * split() for a common "defaultGen" SplittableRandom.  Unlike
142 >     * other cases, this split must be performed in a thread-safe
143 >     * manner, so we use an AtomicLong to represent the seed rather
144 >     * than use an explicit SplittableRandom. To bootstrap the
145 >     * defaultGen, we start off using a seed based on current time and
146 >     * network interface address unless the java.util.secureRandomSeed
147 >     * property is set. This serves as a slimmed-down (and insecure)
148 >     * variant of SecureRandom that also avoids stalls that may occur
149 >     * when using /dev/random.
150 >     *
151 >     * It is a relatively simple matter to apply the basic design here
152 >     * to use 128 bit seeds. However, emulating 128bit arithmetic and
153 >     * carrying around twice the state add more overhead than appears
154 >     * warranted for current usages.
155       *
156 <     * The primary update step (see method nextSeed()) is simply to
157 <     * add a constant ("gamma") to the current seed, modulo a prime
158 <     * ("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.
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 <     * not calls to nextSeed(): Each instance carries the state of
119 <     * 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.
156 >     * File organization: First the non-public methods that constitute
157 >     * the main algorithm, then the main public methods, followed by
158 >     * some custom spliterator classes needed for stream methods.
159       */
180    private static final long DEFAULT_SEED_GAMMA = 0xBD24B73A95FB84D9L;
160  
161      /**
162 <     * The least non-zero value returned by nextDouble(). This value
163 <     * is scaled by a random value of 53 bits to produce a result.
162 >     * The golden ratio scaled to 64bits, used as the initial gamma
163 >     * value for (unsplit) SplittableRandoms.
164       */
165 <    private static final double DOUBLE_UNIT = 1.0 / (1L << 53);
165 >    private static final long GOLDEN_GAMMA = 0x9e3779b97f4a7c15L;
166  
167      /**
168 <     * The next seed for default constructors.
168 >     * The least non-zero value returned by nextDouble(). This value
169 >     * is scaled by a random value of 53 bits to produce a result.
170       */
171 <    private static final AtomicLong defaultSeedGenerator =
192 <        new AtomicLong(System.nanoTime());
171 >    private static final double DOUBLE_ULP = 1.0 / (1L << 53);
172  
173      /**
174 <     * The seed, updated only via method nextSeed.
174 >     * The seed. Updated only via method nextSeed.
175       */
176      private long seed;
177  
178      /**
179 <     * The constant value added to seed (mod George) on each update.
179 >     * The step value.
180       */
181      private final long gamma;
182  
183      /**
184 <     * 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)
184 >     * Internal constructor used by all others except default constructor.
185       */
186 <    private static long addGammaModGeorge(long s, long g) {
187 <        long p = s + g;
188 <        if (Long.compareUnsigned(p, g) >= 0)
226 <            return p;
227 <        long q = p - 13L;
228 <        return (Long.compareUnsigned(p, 13L) >= 0) ? q : (q + g);
186 >    private SplittableRandom(long seed, long gamma) {
187 >        this.seed = seed;
188 >        this.gamma = gamma;
189      }
190  
191      /**
192 <     * Returns a bit-mixed transformation of its argument.
233 <     * See above for explanation.
192 >     * Computes Stafford variant 13 of 64bit mix function.
193       */
194      private static long mix64(long z) {
195 <        z ^= (z >>> 33);
196 <        z *= 0xff51afd7ed558ccdL;
197 <        z ^= (z >>> 33);
239 <        z *= 0xc4ceb9fe1a85ec53L;
240 <        z ^= (z >>> 33);
241 <        return z;
195 >        z *= 0xbf58476d1ce4e5b9L;
196 >        z = (z ^ (z >>> 32)) * 0x94d049bb133111ebL;
197 >        return z ^ (z >>> 32);
198      }
199  
200      /**
201 <     * Returns a bit-mixed int transformation of its argument.
246 <     * See above for explanation.
201 >     * Returns the 32 high bits of Stafford variant 4 mix64 function as int.
202       */
203      private static int mix32(long z) {
204 <        z ^= (z >>> 33);
205 <        z *= 0xc4ceb9fe1a85ec53L;
251 <        return (int)(z >>> 32);
204 >        z *= 0x62a9d9ed799705f5L;
205 >        return (int)(((z ^ (z >>> 28)) * 0xcb24d0a5c88c35b3L) >>> 32);
206      }
207  
208      /**
209 <     * 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.
209 >     * Returns the gamma value to use for a new split instance.
210       */
211 <    private SplittableRandom(long seed, long splitSeed) {
212 <        this.seed = seed;
213 <        long s = splitSeed, g;
214 <        do { // ensure gamma >= 13, considered as an unsigned integer
215 <            s = addGammaModGeorge(s, GAMMA_GAMMA);
216 <            g = mix64(s);
267 <        } while (Long.compareUnsigned(g, 13L) < 0);
268 <        this.gamma = g;
269 <        this.nextSplit = s;
211 >    private static long mixGamma(long z) {
212 >        z *= 0xff51afd7ed558ccdL;                   // MurmurHash3 mix constants
213 >        z = (z ^ (z >>> 33)) * 0xc4ceb9fe1a85ec53L;
214 >        z = (z ^ (z >>> 33)) | 1L;                  // force to be odd
215 >        int n = Long.bitCount(z ^ (z >>> 1));       // ensure enough transitions
216 >        return (n < 24) ? z ^ 0xaaaaaaaaaaaaaaaaL : z;
217      }
218  
219      /**
220 <     * Updates in-place and returns seed.
274 <     * See above for explanation.
220 >     * Adds gamma to seed.
221       */
222      private long nextSeed() {
223 <        return seed = addGammaModGeorge(seed, gamma);
223 >        return seed += gamma;
224      }
225  
226      /**
227 <     * Atomically updates and returns next seed for default constructor.
227 >     * The seed generator for default constructors.
228       */
229 <    private static long nextDefaultSeed() {
230 <        long oldSeed, newSeed;
231 <        do {
232 <            oldSeed = defaultSeedGenerator.get();
233 <            newSeed = addGammaModGeorge(oldSeed, DEFAULT_SEED_GAMMA);
234 <        } while (!defaultSeedGenerator.compareAndSet(oldSeed, newSeed));
235 <        return mix64(newSeed);
229 >    private static final AtomicLong defaultGen = new AtomicLong(initialSeed());
230 >
231 >    private static long initialSeed() {
232 >        String pp = java.security.AccessController.doPrivileged(
233 >                new sun.security.action.GetPropertyAction(
234 >                        "java.util.secureRandomSeed"));
235 >        if (pp != null && pp.equalsIgnoreCase("true")) {
236 >            byte[] seedBytes = java.security.SecureRandom.getSeed(8);
237 >            long s = (long)(seedBytes[0]) & 0xffL;
238 >            for (int i = 1; i < 8; ++i)
239 >                s = (s << 8) | ((long)(seedBytes[i]) & 0xffL);
240 >            return s;
241 >        }
242 >        long h = 0L;
243 >        try {
244 >            Enumeration<NetworkInterface> ifcs =
245 >                NetworkInterface.getNetworkInterfaces();
246 >            boolean retry = false; // retry once if getHardwareAddress is null
247 >            while (ifcs.hasMoreElements()) {
248 >                NetworkInterface ifc = ifcs.nextElement();
249 >                if (!ifc.isVirtual()) { // skip fake addresses
250 >                    byte[] bs = ifc.getHardwareAddress();
251 >                    if (bs != null) {
252 >                        int n = bs.length;
253 >                        int m = Math.min(n >>> 1, 4);
254 >                        for (int i = 0; i < m; ++i)
255 >                            h = (h << 16) ^ (bs[i] << 8) ^ bs[n-1-i];
256 >                        if (m < 4)
257 >                            h = (h << 8) ^ bs[n-1-m];
258 >                        h = mix64(h);
259 >                        break;
260 >                    }
261 >                    else if (!retry)
262 >                        retry = true;
263 >                    else
264 >                        break;
265 >                }
266 >            }
267 >        } catch (Exception ignore) {
268 >        }
269 >        return (h ^ mix64(System.currentTimeMillis()) ^
270 >                mix64(System.nanoTime()));
271      }
272  
273 +    // IllegalArgumentException messages
274 +    static final String BadBound = "bound must be positive";
275 +    static final String BadRange = "bound must be greater than origin";
276 +    static final String BadSize  = "size must be non-negative";
277 +
278      /*
279       * Internal versions of nextX methods used by streams, as well as
280       * the public nextX(origin, bound) methods.  These exist mainly to
# Line 364 | Line 350 | public class SplittableRandom {
350          int r = mix32(nextSeed());
351          if (origin < bound) {
352              int n = bound - origin, m = n - 1;
353 <            if ((n & m) == 0L)
353 >            if ((n & m) == 0)
354                  r = (r & m) + origin;
355              else if (n > 0) {
356                  for (int u = r >>> 1;
# Line 389 | Line 375 | public class SplittableRandom {
375       * @return a pseudorandom value
376       */
377      final double internalNextDouble(double origin, double bound) {
378 <        double r = (nextLong() >>> 11) * DOUBLE_UNIT;
378 >        double r = (nextLong() >>> 11) * DOUBLE_ULP;
379          if (origin < bound) {
380              r = r * (bound - origin) + origin;
381              if (r >= bound) // correct for rounding
# Line 403 | Line 389 | public class SplittableRandom {
389      /**
390       * Creates a new SplittableRandom instance using the specified
391       * initial seed. SplittableRandom instances created with the same
392 <     * seed generate identical sequences of values.
392 >     * seed in the same program generate identical sequences of values.
393       *
394       * @param seed the initial seed
395       */
396      public SplittableRandom(long seed) {
397 <        this(seed, 0);
397 >        this(seed, GOLDEN_GAMMA);
398      }
399  
400      /**
# Line 417 | Line 403 | public class SplittableRandom {
403       * of those of any other instances in the current program; and
404       * may, and typically does, vary across program invocations.
405       */
406 <    public SplittableRandom() {
407 <        this(nextDefaultSeed(), GAMMA_GAMMA);
406 >    public SplittableRandom() { // emulate defaultGen.split()
407 >        long s = defaultGen.getAndAdd(2*GOLDEN_GAMMA);
408 >        this.seed = mix64(s);
409 >        this.gamma = mixGamma(s + GOLDEN_GAMMA);
410      }
411  
412      /**
# Line 436 | Line 424 | public class SplittableRandom {
424       * @return the new SplittableRandom instance
425       */
426      public SplittableRandom split() {
427 <        return new SplittableRandom(nextSeed(), nextSplit);
427 >        return new SplittableRandom(nextLong(), mixGamma(nextSeed()));
428      }
429  
430      /**
# Line 452 | Line 440 | public class SplittableRandom {
440       * Returns a pseudorandom {@code int} value between zero (inclusive)
441       * and the specified bound (exclusive).
442       *
443 <     * @param bound the bound on the random number to be returned.  Must be
456 <     *        positive.
443 >     * @param bound the upper bound (exclusive).  Must be positive.
444       * @return a pseudorandom {@code int} value between zero
445       *         (inclusive) and the bound (exclusive)
446 <     * @throws IllegalArgumentException if the bound is less than zero
446 >     * @throws IllegalArgumentException if {@code bound} is not positive
447       */
448      public int nextInt(int bound) {
449          if (bound <= 0)
450 <            throw new IllegalArgumentException("bound must be positive");
450 >            throw new IllegalArgumentException(BadBound);
451          // Specialize internalNextInt for origin 0
452          int r = mix32(nextSeed());
453          int m = bound - 1;
454 <        if ((bound & m) == 0L) // power of two
454 >        if ((bound & m) == 0) // power of two
455              r &= m;
456          else { // reject over-represented candidates
457              for (int u = r >>> 1;
# Line 488 | Line 475 | public class SplittableRandom {
475       */
476      public int nextInt(int origin, int bound) {
477          if (origin >= bound)
478 <            throw new IllegalArgumentException("bound must be greater than origin");
478 >            throw new IllegalArgumentException(BadRange);
479          return internalNextInt(origin, bound);
480      }
481  
# Line 505 | Line 492 | public class SplittableRandom {
492       * Returns a pseudorandom {@code long} value between zero (inclusive)
493       * and the specified bound (exclusive).
494       *
495 <     * @param bound the bound on the random number to be returned.  Must be
509 <     *        positive.
495 >     * @param bound the upper bound (exclusive).  Must be positive.
496       * @return a pseudorandom {@code long} value between zero
497       *         (inclusive) and the bound (exclusive)
498 <     * @throws IllegalArgumentException if {@code bound} is less than zero
498 >     * @throws IllegalArgumentException if {@code bound} is not positive
499       */
500      public long nextLong(long bound) {
501          if (bound <= 0)
502 <            throw new IllegalArgumentException("bound must be positive");
502 >            throw new IllegalArgumentException(BadBound);
503          // Specialize internalNextLong for origin 0
504          long r = mix64(nextSeed());
505          long m = bound - 1;
# Line 541 | Line 527 | public class SplittableRandom {
527       */
528      public long nextLong(long origin, long bound) {
529          if (origin >= bound)
530 <            throw new IllegalArgumentException("bound must be greater than origin");
530 >            throw new IllegalArgumentException(BadRange);
531          return internalNextLong(origin, bound);
532      }
533  
# Line 550 | Line 536 | public class SplittableRandom {
536       * (inclusive) and one (exclusive).
537       *
538       * @return a pseudorandom {@code double} value between zero
539 <     * (inclusive) and one (exclusive)
539 >     *         (inclusive) and one (exclusive)
540       */
541      public double nextDouble() {
542 <        return (nextLong() >>> 11) * DOUBLE_UNIT;
542 >        return (mix64(nextSeed()) >>> 11) * DOUBLE_ULP;
543      }
544  
545      /**
546       * Returns a pseudorandom {@code double} value between 0.0
547       * (inclusive) and the specified bound (exclusive).
548       *
549 <     * @param bound the bound on the random number to be returned.  Must be
564 <     *        positive.
549 >     * @param bound the upper bound (exclusive).  Must be positive.
550       * @return a pseudorandom {@code double} value between zero
551       *         (inclusive) and the bound (exclusive)
552 <     * @throws IllegalArgumentException if {@code bound} is less than zero
552 >     * @throws IllegalArgumentException if {@code bound} is not positive
553       */
554      public double nextDouble(double bound) {
555          if (!(bound > 0.0))
556 <            throw new IllegalArgumentException("bound must be positive");
557 <        double result = nextDouble() * bound;
556 >            throw new IllegalArgumentException(BadBound);
557 >        double result = (mix64(nextSeed()) >>> 11) * DOUBLE_ULP * bound;
558          return (result < bound) ?  result : // correct for rounding
559              Double.longBitsToDouble(Double.doubleToLongBits(bound) - 1);
560      }
# Line 579 | Line 564 | public class SplittableRandom {
564       * origin (inclusive) and bound (exclusive).
565       *
566       * @param origin the least value returned
567 <     * @param bound the upper bound
567 >     * @param bound the upper bound (exclusive)
568       * @return a pseudorandom {@code double} value between the origin
569       *         (inclusive) and the bound (exclusive)
570       * @throws IllegalArgumentException if {@code origin} is greater than
# Line 587 | Line 572 | public class SplittableRandom {
572       */
573      public double nextDouble(double origin, double bound) {
574          if (!(origin < bound))
575 <            throw new IllegalArgumentException("bound must be greater than origin");
575 >            throw new IllegalArgumentException(BadRange);
576          return internalNextDouble(origin, bound);
577      }
578  
579 +    /**
580 +     * Returns a pseudorandom {@code boolean} value.
581 +     *
582 +     * @return a pseudorandom {@code boolean} value
583 +     */
584 +    public boolean nextBoolean() {
585 +        return mix32(nextSeed()) < 0;
586 +    }
587 +
588      // stream methods, coded in a way intended to better isolate for
589      // maintenance purposes the small differences across forms.
590  
591      /**
592 <     * Returns a stream producing the given {@code streamSize} number of
593 <     * pseudorandom {@code int} values.
592 >     * Returns a stream producing the given {@code streamSize} number
593 >     * of pseudorandom {@code int} values from this generator and/or
594 >     * one split from it.
595       *
596       * @param streamSize the number of values to generate
597       * @return a stream of pseudorandom {@code int} values
# Line 605 | Line 600 | public class SplittableRandom {
600       */
601      public IntStream ints(long streamSize) {
602          if (streamSize < 0L)
603 <            throw new IllegalArgumentException("negative Stream size");
603 >            throw new IllegalArgumentException(BadSize);
604          return StreamSupport.intStream
605              (new RandomIntsSpliterator
606               (this, 0L, streamSize, Integer.MAX_VALUE, 0),
# Line 614 | Line 609 | public class SplittableRandom {
609  
610      /**
611       * Returns an effectively unlimited stream of pseudorandom {@code int}
612 <     * values.
612 >     * values from this generator and/or one split from it.
613       *
614       * @implNote This method is implemented to be equivalent to {@code
615       * ints(Long.MAX_VALUE)}.
# Line 629 | Line 624 | public class SplittableRandom {
624      }
625  
626      /**
627 <     * Returns a stream producing the given {@code streamSize} number of
628 <     * pseudorandom {@code int} values, each conforming to the given
629 <     * origin and bound.
627 >     * Returns a stream producing the given {@code streamSize} number
628 >     * of pseudorandom {@code int} values from this generator and/or one split
629 >     * from it; each value conforms to the given origin (inclusive) and bound
630 >     * (exclusive).
631       *
632       * @param streamSize the number of values to generate
633 <     * @param randomNumberOrigin the origin of each random value
634 <     * @param randomNumberBound the bound of each random value
633 >     * @param randomNumberOrigin the origin (inclusive) of each random value
634 >     * @param randomNumberBound the bound (exclusive) of each random value
635       * @return a stream of pseudorandom {@code int} values,
636 <     *         each with the given origin and bound
636 >     *         each with the given origin (inclusive) and bound (exclusive)
637       * @throws IllegalArgumentException if {@code streamSize} is
638       *         less than zero, or {@code randomNumberOrigin}
639       *         is greater than or equal to {@code randomNumberBound}
# Line 645 | Line 641 | public class SplittableRandom {
641      public IntStream ints(long streamSize, int randomNumberOrigin,
642                            int randomNumberBound) {
643          if (streamSize < 0L)
644 <            throw new IllegalArgumentException("negative Stream size");
644 >            throw new IllegalArgumentException(BadSize);
645          if (randomNumberOrigin >= randomNumberBound)
646 <            throw new IllegalArgumentException("bound must be greater than origin");
646 >            throw new IllegalArgumentException(BadRange);
647          return StreamSupport.intStream
648              (new RandomIntsSpliterator
649               (this, 0L, streamSize, randomNumberOrigin, randomNumberBound),
# Line 656 | Line 652 | public class SplittableRandom {
652  
653      /**
654       * Returns an effectively unlimited stream of pseudorandom {@code
655 <     * int} values, each conforming to the given origin and bound.
655 >     * int} values from this generator and/or one split from it; each value
656 >     * conforms to the given origin (inclusive) and bound (exclusive).
657       *
658       * @implNote This method is implemented to be equivalent to {@code
659       * ints(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
660       *
661 <     * @param randomNumberOrigin the origin of each random value
662 <     * @param randomNumberBound the bound of each random value
661 >     * @param randomNumberOrigin the origin (inclusive) of each random value
662 >     * @param randomNumberBound the bound (exclusive) of each random value
663       * @return a stream of pseudorandom {@code int} values,
664 <     *         each with the given origin and bound
664 >     *         each with the given origin (inclusive) and bound (exclusive)
665       * @throws IllegalArgumentException if {@code randomNumberOrigin}
666       *         is greater than or equal to {@code randomNumberBound}
667       */
668      public IntStream ints(int randomNumberOrigin, int randomNumberBound) {
669          if (randomNumberOrigin >= randomNumberBound)
670 <            throw new IllegalArgumentException("bound must be greater than origin");
670 >            throw new IllegalArgumentException(BadRange);
671          return StreamSupport.intStream
672              (new RandomIntsSpliterator
673               (this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
# Line 678 | Line 675 | public class SplittableRandom {
675      }
676  
677      /**
678 <     * Returns a stream producing the given {@code streamSize} number of
679 <     * pseudorandom {@code long} values.
678 >     * Returns a stream producing the given {@code streamSize} number
679 >     * of pseudorandom {@code long} values from this generator and/or
680 >     * one split from it.
681       *
682       * @param streamSize the number of values to generate
683       * @return a stream of pseudorandom {@code long} values
# Line 688 | Line 686 | public class SplittableRandom {
686       */
687      public LongStream longs(long streamSize) {
688          if (streamSize < 0L)
689 <            throw new IllegalArgumentException("negative Stream size");
689 >            throw new IllegalArgumentException(BadSize);
690          return StreamSupport.longStream
691              (new RandomLongsSpliterator
692               (this, 0L, streamSize, Long.MAX_VALUE, 0L),
# Line 696 | Line 694 | public class SplittableRandom {
694      }
695  
696      /**
697 <     * Returns an effectively unlimited stream of pseudorandom {@code long}
698 <     * values.
697 >     * Returns an effectively unlimited stream of pseudorandom {@code
698 >     * long} values from this generator and/or one split from it.
699       *
700       * @implNote This method is implemented to be equivalent to {@code
701       * longs(Long.MAX_VALUE)}.
# Line 713 | Line 711 | public class SplittableRandom {
711  
712      /**
713       * Returns a stream producing the given {@code streamSize} number of
714 <     * pseudorandom {@code long} values, each conforming to the
715 <     * given origin and bound.
714 >     * pseudorandom {@code long} values from this generator and/or one split
715 >     * from it; each value conforms to the given origin (inclusive) and bound
716 >     * (exclusive).
717       *
718       * @param streamSize the number of values to generate
719 <     * @param randomNumberOrigin the origin of each random value
720 <     * @param randomNumberBound the bound of each random value
719 >     * @param randomNumberOrigin the origin (inclusive) of each random value
720 >     * @param randomNumberBound the bound (exclusive) of each random value
721       * @return a stream of pseudorandom {@code long} values,
722 <     *         each with the given origin and bound
722 >     *         each with the given origin (inclusive) and bound (exclusive)
723       * @throws IllegalArgumentException if {@code streamSize} is
724       *         less than zero, or {@code randomNumberOrigin}
725       *         is greater than or equal to {@code randomNumberBound}
# Line 728 | Line 727 | public class SplittableRandom {
727      public LongStream longs(long streamSize, long randomNumberOrigin,
728                              long randomNumberBound) {
729          if (streamSize < 0L)
730 <            throw new IllegalArgumentException("negative Stream size");
730 >            throw new IllegalArgumentException(BadSize);
731          if (randomNumberOrigin >= randomNumberBound)
732 <            throw new IllegalArgumentException("bound must be greater than origin");
732 >            throw new IllegalArgumentException(BadRange);
733          return StreamSupport.longStream
734              (new RandomLongsSpliterator
735               (this, 0L, streamSize, randomNumberOrigin, randomNumberBound),
# Line 739 | Line 738 | public class SplittableRandom {
738  
739      /**
740       * Returns an effectively unlimited stream of pseudorandom {@code
741 <     * long} values, each conforming to the given origin and bound.
741 >     * long} values from this generator and/or one split from it; each value
742 >     * conforms to the given origin (inclusive) and bound (exclusive).
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
747 >     * @param randomNumberOrigin the origin (inclusive) of each random value
748 >     * @param randomNumberBound the bound (exclusive) of each random value
749       * @return a stream of pseudorandom {@code long} values,
750 <     *         each with the given origin and bound
750 >     *         each with the given origin (inclusive) and bound (exclusive)
751       * @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");
756 >            throw new IllegalArgumentException(BadRange);
757          return StreamSupport.longStream
758              (new RandomLongsSpliterator
759               (this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
# Line 762 | Line 762 | public class SplittableRandom {
762  
763      /**
764       * Returns a stream producing the given {@code streamSize} number of
765 <     * pseudorandom {@code double} values, each between zero
766 <     * (inclusive) and one (exclusive).
765 >     * pseudorandom {@code double} values from this generator and/or one split
766 >     * from it; each value is between zero (inclusive) and one (exclusive).
767       *
768       * @param streamSize the number of values to generate
769       * @return a stream of {@code double} values
# Line 772 | Line 772 | public class SplittableRandom {
772       */
773      public DoubleStream doubles(long streamSize) {
774          if (streamSize < 0L)
775 <            throw new IllegalArgumentException("negative Stream size");
775 >            throw new IllegalArgumentException(BadSize);
776          return StreamSupport.doubleStream
777              (new RandomDoublesSpliterator
778               (this, 0L, streamSize, Double.MAX_VALUE, 0.0),
# Line 781 | Line 781 | public class SplittableRandom {
781  
782      /**
783       * Returns an effectively unlimited stream of pseudorandom {@code
784 <     * double} values, each between zero (inclusive) and one
785 <     * (exclusive).
784 >     * double} values from this generator and/or one split from it; each value
785 >     * is between zero (inclusive) and one (exclusive).
786       *
787       * @implNote This method is implemented to be equivalent to {@code
788       * doubles(Long.MAX_VALUE)}.
# Line 798 | Line 798 | public class SplittableRandom {
798  
799      /**
800       * Returns a stream producing the given {@code streamSize} number of
801 <     * pseudorandom {@code double} values, each conforming to the
802 <     * given origin and bound.
801 >     * pseudorandom {@code double} values from this generator and/or one split
802 >     * from it; each value conforms to the given origin (inclusive) and bound
803 >     * (exclusive).
804       *
805       * @param streamSize the number of values to generate
806 <     * @param randomNumberOrigin the origin of each random value
807 <     * @param randomNumberBound the bound of each random value
806 >     * @param randomNumberOrigin the origin (inclusive) of each random value
807 >     * @param randomNumberBound the bound (exclusive) of each random value
808       * @return a stream of pseudorandom {@code double} values,
809 <     * each with the given origin and bound
809 >     *         each with the given origin (inclusive) and bound (exclusive)
810       * @throws IllegalArgumentException if {@code streamSize} is
811 <     * less than zero
811 >     *         less than zero
812       * @throws IllegalArgumentException if {@code randomNumberOrigin}
813       *         is greater than or equal to {@code randomNumberBound}
814       */
815      public DoubleStream doubles(long streamSize, double randomNumberOrigin,
816                                  double randomNumberBound) {
817          if (streamSize < 0L)
818 <            throw new IllegalArgumentException("negative Stream size");
818 >            throw new IllegalArgumentException(BadSize);
819          if (!(randomNumberOrigin < randomNumberBound))
820 <            throw new IllegalArgumentException("bound must be greater than origin");
820 >            throw new IllegalArgumentException(BadRange);
821          return StreamSupport.doubleStream
822              (new RandomDoublesSpliterator
823               (this, 0L, streamSize, randomNumberOrigin, randomNumberBound),
# Line 825 | Line 826 | public class SplittableRandom {
826  
827      /**
828       * Returns an effectively unlimited stream of pseudorandom {@code
829 <     * double} values, each conforming to the given origin and bound.
829 >     * double} values from this generator and/or one split from it; each value
830 >     * conforms to the given origin (inclusive) and bound (exclusive).
831       *
832       * @implNote This method is implemented to be equivalent to {@code
833       * doubles(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
834       *
835 <     * @param randomNumberOrigin the origin of each random value
836 <     * @param randomNumberBound the bound of each random value
835 >     * @param randomNumberOrigin the origin (inclusive) of each random value
836 >     * @param randomNumberBound the bound (exclusive) of each random value
837       * @return a stream of pseudorandom {@code double} values,
838 <     * each with the given origin and bound
838 >     *         each with the given origin (inclusive) and bound (exclusive)
839       * @throws IllegalArgumentException if {@code randomNumberOrigin}
840       *         is greater than or equal to {@code randomNumberBound}
841       */
842      public DoubleStream doubles(double randomNumberOrigin, double randomNumberBound) {
843          if (!(randomNumberOrigin < randomNumberBound))
844 <            throw new IllegalArgumentException("bound must be greater than origin");
844 >            throw new IllegalArgumentException(BadRange);
845          return StreamSupport.doubleStream
846              (new RandomDoublesSpliterator
847               (this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
# Line 854 | Line 856 | public class SplittableRandom {
856       * approach. The long and double versions of this class are
857       * identical except for types.
858       */
859 <    static class RandomIntsSpliterator implements Spliterator.OfInt {
859 >    static final class RandomIntsSpliterator implements Spliterator.OfInt {
860          final SplittableRandom rng;
861          long index;
862          final long fence;
# Line 897 | Line 899 | public class SplittableRandom {
899              long i = index, f = fence;
900              if (i < f) {
901                  index = f;
902 +                SplittableRandom r = rng;
903                  int o = origin, b = bound;
904                  do {
905 <                    consumer.accept(rng.internalNextInt(o, b));
905 >                    consumer.accept(r.internalNextInt(o, b));
906                  } while (++i < f);
907              }
908          }
# Line 908 | Line 911 | public class SplittableRandom {
911      /**
912       * Spliterator for long streams.
913       */
914 <    static class RandomLongsSpliterator implements Spliterator.OfLong {
914 >    static final class RandomLongsSpliterator implements Spliterator.OfLong {
915          final SplittableRandom rng;
916          long index;
917          final long fence;
# Line 951 | Line 954 | public class SplittableRandom {
954              long i = index, f = fence;
955              if (i < f) {
956                  index = f;
957 +                SplittableRandom r = rng;
958                  long o = origin, b = bound;
959                  do {
960 <                    consumer.accept(rng.internalNextLong(o, b));
960 >                    consumer.accept(r.internalNextLong(o, b));
961                  } while (++i < f);
962              }
963          }
# Line 963 | Line 967 | public class SplittableRandom {
967      /**
968       * Spliterator for double streams.
969       */
970 <    static class RandomDoublesSpliterator implements Spliterator.OfDouble {
970 >    static final class RandomDoublesSpliterator implements Spliterator.OfDouble {
971          final SplittableRandom rng;
972          long index;
973          final long fence;
# Line 1006 | Line 1010 | public class SplittableRandom {
1010              long i = index, f = fence;
1011              if (i < f) {
1012                  index = f;
1013 +                SplittableRandom r = rng;
1014                  double o = origin, b = bound;
1015                  do {
1016 <                    consumer.accept(rng.internalNextDouble(o, b));
1016 >                    consumer.accept(r.internalNextDouble(o, b));
1017                  } while (++i < f);
1018              }
1019          }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines