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.13 by dl, Thu Jul 25 13:19:09 2013 UTC vs.
Revision 1.23 by dl, Fri Sep 20 14:06:46 2013 UTC

# Line 25 | Line 25
25  
26   package java.util;
27  
28 < import java.security.SecureRandom;
28 > import java.net.NetworkInterface;
29   import java.util.concurrent.atomic.AtomicLong;
30 import java.util.Spliterator;
30   import java.util.function.IntConsumer;
31   import java.util.function.LongConsumer;
32   import java.util.function.DoubleConsumer;
# Line 39 | Line 38 | import java.util.stream.DoubleStream;
38   /**
39   * A generator of uniform pseudorandom values applicable for use in
40   * (among other contexts) isolated parallel computations that may
41 < * generate subtasks. Class SplittableRandom supports methods for
41 > * generate subtasks. Class {@code SplittableRandom} supports methods for
42   * producing pseudorandom numbers of type {@code int}, {@code long},
43   * and {@code double} with similar usages as for class
44   * {@link java.util.Random} but differs in the following ways:
# Line 77 | Line 76 | import java.util.stream.DoubleStream;
76   *
77   * </ul>
78   *
79 + * <p>Instances of {@code SplittableRandom} are not cryptographically
80 + * secure.  Consider instead using {@link java.security.SecureRandom}
81 + * in security-sensitive applications. Additionally,
82 + * default-constructed instances do not use a cryptographically random
83 + * seed unless the {@linkplain System#getProperty system property}
84 + * {@code java.util.secureRandomSeed} is set to {@code true}.
85 + *
86   * @author  Guy Steele
87   * @author  Doug Lea
88   * @since   1.8
89   */
90 < public class SplittableRandom {
85 <
86 <    /*
87 <     * File organization: First the non-public methods that constitute
88 <     * the main algorithm, then the main public methods, followed by
89 <     * some custom spliterator classes needed for stream methods.
90 <     *
91 <     * Credits: Primary algorithm and code by Guy Steele.  Stream
92 <     * support methods by Doug Lea.  Documentation jointly produced
93 <     * with additional help from Brian Goetz.
94 <     */
90 > public final class SplittableRandom {
91  
92      /*
93       * Implementation Overview.
# Line 99 | Line 95 | public class SplittableRandom {
95       * This algorithm was inspired by the "DotMix" algorithm by
96       * Leiserson, Schardl, and Sukha "Deterministic Parallel
97       * Random-Number Generation for Dynamic-Multithreading Platforms",
98 <     * PPoPP 2012, but improves and extends it in several ways.
98 >     * PPoPP 2012, as well as those in "Parallel random numbers: as
99 >     * easy as 1, 2, 3" by Salmon, Morae, Dror, and Shaw, SC 2011.  It
100 >     * differs mainly in simplifying and cheapening operations.
101 >     *
102 >     * The primary update step (method nextSeed()) is to add a
103 >     * constant ("gamma") to the current (64 bit) seed, forming a
104 >     * simple sequence.  The seed and the gamma values for any two
105 >     * SplittableRandom instances are highly likely to be different.
106 >     *
107 >     * Methods nextLong, nextInt, and derivatives do not return the
108 >     * sequence (seed) values, but instead a hash-like bit-mix of
109 >     * their bits, producing more independently distributed sequences.
110 >     * For nextLong, the mix64 function is based on David Stafford's
111 >     * (http://zimbry.blogspot.com/2011/09/better-bit-mixing-improving-on.html)
112 >     * "Mix13" variant of the "64-bit finalizer" function in Austin
113 >     * Appleby's MurmurHash3 algorithm See
114 >     * http://code.google.com/p/smhasher/wiki/MurmurHash3 . The mix32
115 >     * function is based on Stafford's Mix04 mix function, but returns
116 >     * the upper 32 bits cast as int.
117 >     *
118 >     * The split operation uses the current generator to form the seed
119 >     * and gamma for another SplittableRandom.  To conservatively
120 >     * avoid potential correlations between seed and value generation,
121 >     * gamma selection (method mixGamma) uses different
122 >     * (Murmurhash3's) mix constants.  To avoid potential weaknesses
123 >     * in bit-mixing transformations, we restrict gammas to odd values
124 >     * with at least 24 0-1 or 1-0 bit transitions.  Rather than
125 >     * rejecting candidates with too few or too many bits set, method
126 >     * mixGamma flips some bits (which has the effect of mapping at
127 >     * most 4 to any given gamma value).  This reduces the effective
128 >     * set of 64bit odd gamma values by about 2%, and serves as an
129 >     * automated screening for sequence constant selection that is
130 >     * left as an empirical decision in some other hashing and crypto
131 >     * algorithms.
132 >     *
133 >     * The resulting generator thus transforms a sequence in which
134 >     * (typically) many bits change on each step, with an inexpensive
135 >     * mixer with good (but less than cryptographically secure)
136 >     * avalanching.
137 >     *
138 >     * The default (no-argument) constructor, in essence, invokes
139 >     * split() for a common "defaultGen" SplittableRandom.  Unlike
140 >     * other cases, this split must be performed in a thread-safe
141 >     * manner, so we use an AtomicLong to represent the seed rather
142 >     * than use an explicit SplittableRandom. To bootstrap the
143 >     * defaultGen, we start off using a seed based on current time and
144 >     * network interface address unless the java.util.secureRandomSeed
145 >     * property is set. This serves as a slimmed-down (and insecure)
146 >     * variant of SecureRandom that also avoids stalls that may occur
147 >     * when using /dev/random.
148 >     *
149 >     * It is a relatively simple matter to apply the basic design here
150 >     * to use 128 bit seeds. However, emulating 128bit arithmetic and
151 >     * carrying around twice the state add more overhead than appears
152 >     * warranted for current usages.
153       *
154 <     * The primary update step (see method nextSeed()) is simply to
155 <     * add a constant ("gamma") to the current seed, modulo a prime
156 <     * ("George"). However, the nextLong and nextInt methods do not
107 <     * return this value, but instead the results of bit-mixing
108 <     * transformations that produce more uniformly distributed
109 <     * sequences.
110 <     *
111 <     * "George" is the otherwise nameless (because it cannot be
112 <     * represented) prime number 2^64+13. Using a prime number larger
113 <     * than can fit in a long ensures that all possible long values
114 <     * can occur, plus 13 others that just get skipped over when they
115 <     * are encountered; see method addGammaModGeorge. For this to
116 <     * work, initial gamma values must be at least 13.
117 <     *
118 <     * The mix64 bit-mixing function called by nextLong and other
119 <     * methods computes the same value as the "64-bit finalizer"
120 <     * function in Austin Appleby's MurmurHash3 algorithm.  See
121 <     * http://code.google.com/p/smhasher/wiki/MurmurHash3 , which
122 <     * comments: "The constants for the finalizers were generated by a
123 <     * simple simulated-annealing algorithm, and both avalanche all
124 <     * bits of 'h' to within 0.25% bias."
125 <     *
126 <     * The value of gamma differs for each instance across a series of
127 <     * splits, and is generated using an independent variant of the
128 <     * same algorithm, but operating across calls to split(), not
129 <     * calls to nextSeed(): Each instance carries the state of this
130 <     * generator as nextSplit. Gammas are treated as 57bit values,
131 <     * advancing by adding GAMMA_GAMMA mod GAMMA_PRIME, and bit-mixed
132 <     * with a 57-bit version of mix, using the "Mix01" multiplicative
133 <     * constants for MurmurHash3 described by David Stafford
134 <     * (http://zimbry.blogspot.com/2011/09/better-bit-mixing-improving-on.html).
135 <     * The value of GAMMA_GAMMA is arbitrary (except must be at least
136 <     * 13 and less than GAMMA_PRIME), but because it serves as the
137 <     * base of split sequences, should be subject to validation of
138 <     * consequent random number quality metrics.
139 <     *
140 <     * The mix32 function used for nextInt just consists of two of the
141 <     * five lines of mix64; avalanche testing shows that the 64-bit
142 <     * result has its top 32 bits avalanched well, though not the
143 <     * bottom 32 bits.  DieHarder tests show that it is adequate for
144 <     * generating one random int from the 64-bit result of nextSeed.
145 <     *
146 <     * Support for the default (no-argument) constructor relies on an
147 <     * AtomicLong (defaultSeedGenerator) to help perform the
148 <     * equivalent of a split of a statically constructed
149 <     * SplittableRandom. Unlike other cases, this split must be
150 <     * performed in a thread-safe manner. We use
151 <     * AtomicLong.compareAndSet as the (typically) most efficient
152 <     * mechanism. To bootstrap, we start off using a SecureRandom
153 <     * initial default seed, and update using a fixed
154 <     * DEFAULT_SEED_GAMMA. The default constructor uses GAMMA_GAMMA,
155 <     * not 0, for its splitSeed argument (addGammaModGeorge(0,
156 <     * GAMMA_GAMMA) == GAMMA_GAMMA) to reflect that each is split from
157 <     * this root generator, even though the root is not explicitly
158 <     * represented as a SplittableRandom.
159 <     */
160 <
161 <    /**
162 <     * The prime modulus for gamma values.
163 <     */
164 <    private static final long GAMMA_PRIME = (1L << 57) - 13L;
165 <
166 <    /**
167 <     * The value for producing new gamma values. Must be greater or
168 <     * equal to 13 and less than GAMMA_PRIME. Otherwise, the value is
169 <     * arbitrary subject to validation of the resulting statistical
170 <     * quality of splits.
171 <     */
172 <    private static final long GAMMA_GAMMA = 0x00aae38294f712aabL;
173 <
174 <    /**
175 <     * The seed update value for default constructors.  Must be
176 <     * greater or equal to 13. Otherwise, the value is arbitrary
177 <     * subject to quality checks.
154 >     * File organization: First the non-public methods that constitute
155 >     * the main algorithm, then the main public methods, followed by
156 >     * some custom spliterator classes needed for stream methods.
157       */
179    private static final long DEFAULT_SEED_GAMMA = 0x9e3779b97f4a7c15L;
158  
159      /**
160 <     * The value 13 with 64bit sign bit set. Used in the signed
161 <     * comparison in addGammaModGeorge.
160 >     * The golden ratio scaled to 64bits, used as the initial gamma
161 >     * value for (unsplit) SplittableRandoms.
162       */
163 <    private static final long BOTTOM13 = 0x800000000000000DL;
163 >    private static final long GOLDEN_GAMMA = 0x9e3779b97f4a7c15L;
164  
165      /**
166       * The least non-zero value returned by nextDouble(). This value
167       * is scaled by a random value of 53 bits to produce a result.
168       */
169 <    private static final double DOUBLE_UNIT = 1.0 / (1L << 53);
169 >    private static final double DOUBLE_ULP = 1.0 / (1L << 53);
170  
171      /**
172 <     * The next seed for default constructors.
195 <     */
196 <    private static final AtomicLong defaultSeedGenerator =
197 <        new AtomicLong(getInitialDefaultSeed());
198 <
199 <    /**
200 <     * The seed, updated only via method nextSeed.
172 >     * The seed. Updated only via method nextSeed.
173       */
174      private long seed;
175  
176      /**
177 <     * The constant value added to seed (mod George) on each update.
177 >     * The step value.
178       */
179      private final long gamma;
180  
181      /**
182 <     * The next seed to use for splits. Propagated using
211 <     * addGammaModGeorge across instances.
212 <     */
213 <    private final long nextSplit;
214 <
215 <    /**
216 <     * Adds the given gamma value, g, to the given seed value s, mod
217 <     * George (2^64+13). We regard s and g as unsigned values
218 <     * (ranging from 0 to 2^64-1). We add g to s either once or twice
219 <     * (mod George) as necessary to produce an (unsigned) result less
220 <     * than 2^64.  We require that g must be at least 13. This
221 <     * guarantees that if (s+g) mod George >= 2^64 then (s+g+g) mod
222 <     * George < 2^64; thus we need only a conditional, not a loop,
223 <     * to be sure of getting a representable value.
224 <     *
225 <     * Because Java comparison operators are signed, we implement this
226 <     * by conceptually offsetting seed values downwards by 2^63, so
227 <     * 0..13 is represented as Long.MIN_VALUE..BOTTOM13.
228 <     *
229 <     * @param s a seed value, viewed as a signed long
230 <     * @param g a gamma value, 13 <= g (as unsigned)
182 >     * Internal constructor used by all others except default constructor.
183       */
184 <    private static long addGammaModGeorge(long s, long g) {
185 <        long p = s + g;
186 <        return (p >= s) ? p : ((p >= BOTTOM13) ? p  : p + g) - 13L;
184 >    private SplittableRandom(long seed, long gamma) {
185 >        this.seed = seed;
186 >        this.gamma = gamma;
187      }
188  
189      /**
190 <     * Returns a bit-mixed transformation of its argument.
239 <     * See above for explanation.
190 >     * Computes Stafford variant 13 of 64bit mix function.
191       */
192      private static long mix64(long z) {
193 <        z ^= (z >>> 33);
194 <        z *= 0xff51afd7ed558ccdL;
195 <        z ^= (z >>> 33);
245 <        z *= 0xc4ceb9fe1a85ec53L;
246 <        z ^= (z >>> 33);
247 <        return z;
193 >        z *= 0xbf58476d1ce4e5b9L;
194 >        z = (z ^ (z >>> 32)) * 0x94d049bb133111ebL;
195 >        return z ^ (z >>> 32);
196      }
197  
198      /**
199 <     * Returns a bit-mixed int transformation of its argument.
252 <     * See above for explanation.
199 >     * Returns the 32 high bits of Stafford variant 4 mix64 function as int.
200       */
201      private static int mix32(long z) {
202 <        z ^= (z >>> 33);
203 <        z *= 0xc4ceb9fe1a85ec53L;
257 <        return (int)(z >>> 32);
258 <    }
259 <
260 <    /**
261 <     * Returns a 57-bit mixed transformation of its argument.  See
262 <     * above for explanation.
263 <     */
264 <    private static long mix57(long z) {
265 <        z ^= (z >>> 33);
266 <        z *= 0x7fb5d329728ea185L;
267 <        z &= 0x01FFFFFFFFFFFFFFL;
268 <        z ^= (z >>> 33);
269 <        z *= 0x81dadef4bc2dd44dL;
270 <        z &= 0x01FFFFFFFFFFFFFFL;
271 <        z ^= (z >>> 33);
272 <        return z;
202 >        z *= 0x62a9d9ed799705f5L;
203 >        return (int)(((z ^ (z >>> 28)) * 0xcb24d0a5c88c35b3L) >>> 32);
204      }
205  
206      /**
207 <     * Internal constructor used by all other constructors and by
277 <     * method split. Establishes the initial seed for this instance,
278 <     * and uses the given splitSeed to establish gamma, as well as the
279 <     * nextSplit to use by this instance. The loop to skip ineligible
280 <     * gammas very rarely iterates, and does so at most 13 times.
207 >     * Returns the gamma value to use for a new split instance.
208       */
209 <    private SplittableRandom(long seed, long splitSeed) {
210 <        this.seed = seed;
211 <        long s = splitSeed, g;
212 <        do { // ensure gamma >= 13, considered as an unsigned integer
213 <            s += GAMMA_GAMMA;
214 <            if (s >= GAMMA_PRIME)
288 <                s -= GAMMA_PRIME;
289 <            g = mix57(s);
290 <        } while (g < 13L);
291 <        this.gamma = g;
292 <        this.nextSplit = s;
209 >    private static long mixGamma(long z) {
210 >        z *= 0xff51afd7ed558ccdL;                   // MurmurHash3 mix constants
211 >        z = (z ^ (z >>> 33)) * 0xc4ceb9fe1a85ec53L;
212 >        z = (z ^ (z >>> 33)) | 1L;                  // force to be odd
213 >        int n = Long.bitCount(z ^ (z >>> 1));       // ensure enough transitions
214 >        return (n < 24) ? z ^ 0xaaaaaaaaaaaaaaaaL : z;
215      }
216  
217      /**
218 <     * Updates in-place and returns seed.
297 <     * See above for explanation.
218 >     * Adds gamma to seed.
219       */
220      private long nextSeed() {
221 <        return seed = addGammaModGeorge(seed, gamma);
221 >        return seed += gamma;
222      }
223  
224      /**
225 <     * Atomically updates and returns next seed for default constructor.
225 >     * The seed generator for default constructors.
226       */
227 <    private static long nextDefaultSeed() {
307 <        long oldSeed, newSeed;
308 <        do {
309 <            oldSeed = defaultSeedGenerator.get();
310 <            newSeed = addGammaModGeorge(oldSeed, DEFAULT_SEED_GAMMA);
311 <        } while (!defaultSeedGenerator.compareAndSet(oldSeed, newSeed));
312 <        return mix64(newSeed);
313 <    }
227 >    private static final AtomicLong defaultGen = new AtomicLong(initialSeed());
228  
229 <    /**
230 <     * Returns an initial default seed.
231 <     */
232 <    private static long getInitialDefaultSeed() {
233 <        byte[] seedBytes = java.security.SecureRandom.getSeed(8);
234 <        long s = (long)(seedBytes[0]) & 0xffL;
235 <        for (int i = 1; i < 8; ++i)
236 <            s = (s << 8) | ((long)(seedBytes[i]) & 0xffL);
237 <        return s;
229 >    private static long initialSeed() {
230 >        String pp = java.security.AccessController.doPrivileged(
231 >                new sun.security.action.GetPropertyAction(
232 >                        "java.util.secureRandomSeed"));
233 >        if (pp != null && pp.equalsIgnoreCase("true")) {
234 >            byte[] seedBytes = java.security.SecureRandom.getSeed(8);
235 >            long s = (long)(seedBytes[0]) & 0xffL;
236 >            for (int i = 1; i < 8; ++i)
237 >                s = (s << 8) | ((long)(seedBytes[i]) & 0xffL);
238 >            return s;
239 >        }
240 >        long h = 0L;
241 >        try {
242 >            Enumeration<NetworkInterface> ifcs =
243 >                    NetworkInterface.getNetworkInterfaces();
244 >            boolean retry = false; // retry once if getHardwareAddress is null
245 >            while (ifcs.hasMoreElements()) {
246 >                NetworkInterface ifc = ifcs.nextElement();
247 >                if (!ifc.isVirtual()) { // skip fake addresses
248 >                    byte[] bs = ifc.getHardwareAddress();
249 >                    if (bs != null) {
250 >                        int n = bs.length;
251 >                        int m = Math.min(n >>> 1, 4);
252 >                        for (int i = 0; i < m; ++i)
253 >                            h = (h << 16) ^ (bs[i] << 8) ^ bs[n-1-i];
254 >                        if (m < 4)
255 >                            h = (h << 8) ^ bs[n-1-m];
256 >                        h = mix64(h);
257 >                        break;
258 >                    }
259 >                    else if (!retry)
260 >                        retry = true;
261 >                    else
262 >                        break;
263 >                }
264 >            }
265 >        } catch (Exception ignore) {
266 >        }
267 >        return (h ^ mix64(System.currentTimeMillis()) ^
268 >                mix64(System.nanoTime()));
269      }
270  
271 +    // IllegalArgumentException messages
272 +    static final String BadBound = "bound must be positive";
273 +    static final String BadRange = "bound must be greater than origin";
274 +    static final String BadSize  = "size must be non-negative";
275 +
276      /*
277       * Internal versions of nextX methods used by streams, as well as
278       * the public nextX(origin, bound) methods.  These exist mainly to
# Line 423 | Line 373 | public class SplittableRandom {
373       * @return a pseudorandom value
374       */
375      final double internalNextDouble(double origin, double bound) {
376 <        double r = (nextLong() >>> 11) * DOUBLE_UNIT;
376 >        double r = (nextLong() >>> 11) * DOUBLE_ULP;
377          if (origin < bound) {
378              r = r * (bound - origin) + origin;
379              if (r >= bound) // correct for rounding
# Line 442 | Line 392 | public class SplittableRandom {
392       * @param seed the initial seed
393       */
394      public SplittableRandom(long seed) {
395 <        this(seed, 0L);
395 >        this(seed, GOLDEN_GAMMA);
396      }
397  
398      /**
# Line 451 | Line 401 | public class SplittableRandom {
401       * of those of any other instances in the current program; and
402       * may, and typically does, vary across program invocations.
403       */
404 <    public SplittableRandom() {
405 <        this(nextDefaultSeed(), GAMMA_GAMMA);
404 >    public SplittableRandom() { // emulate defaultGen.split()
405 >        long s = defaultGen.getAndAdd(2 * GOLDEN_GAMMA);
406 >        this.seed = mix64(s);
407 >        this.gamma = mixGamma(s + GOLDEN_GAMMA);
408      }
409  
410      /**
# Line 470 | Line 422 | public class SplittableRandom {
422       * @return the new SplittableRandom instance
423       */
424      public SplittableRandom split() {
425 <        return new SplittableRandom(nextSeed(), nextSplit);
425 >        return new SplittableRandom(nextLong(), mixGamma(nextSeed()));
426      }
427  
428      /**
# Line 486 | Line 438 | public class SplittableRandom {
438       * Returns a pseudorandom {@code int} value between zero (inclusive)
439       * and the specified bound (exclusive).
440       *
441 <     * @param bound the bound on the random number to be returned.  Must be
490 <     *        positive.
441 >     * @param bound the upper bound (exclusive).  Must be positive.
442       * @return a pseudorandom {@code int} value between zero
443       *         (inclusive) and the bound (exclusive)
444 <     * @throws IllegalArgumentException if the bound is less than zero
444 >     * @throws IllegalArgumentException if {@code bound} is not positive
445       */
446      public int nextInt(int bound) {
447          if (bound <= 0)
448 <            throw new IllegalArgumentException("bound must be positive");
448 >            throw new IllegalArgumentException(BadBound);
449          // Specialize internalNextInt for origin 0
450          int r = mix32(nextSeed());
451          int m = bound - 1;
# Line 522 | Line 473 | public class SplittableRandom {
473       */
474      public int nextInt(int origin, int bound) {
475          if (origin >= bound)
476 <            throw new IllegalArgumentException("bound must be greater than origin");
476 >            throw new IllegalArgumentException(BadRange);
477          return internalNextInt(origin, bound);
478      }
479  
# Line 539 | Line 490 | public class SplittableRandom {
490       * Returns a pseudorandom {@code long} value between zero (inclusive)
491       * and the specified bound (exclusive).
492       *
493 <     * @param bound the bound on the random number to be returned.  Must be
543 <     *        positive.
493 >     * @param bound the upper bound (exclusive).  Must be positive.
494       * @return a pseudorandom {@code long} value between zero
495       *         (inclusive) and the bound (exclusive)
496 <     * @throws IllegalArgumentException if {@code bound} is less than zero
496 >     * @throws IllegalArgumentException if {@code bound} is not positive
497       */
498      public long nextLong(long bound) {
499          if (bound <= 0)
500 <            throw new IllegalArgumentException("bound must be positive");
500 >            throw new IllegalArgumentException(BadBound);
501          // Specialize internalNextLong for origin 0
502          long r = mix64(nextSeed());
503          long m = bound - 1;
# Line 575 | Line 525 | public class SplittableRandom {
525       */
526      public long nextLong(long origin, long bound) {
527          if (origin >= bound)
528 <            throw new IllegalArgumentException("bound must be greater than origin");
528 >            throw new IllegalArgumentException(BadRange);
529          return internalNextLong(origin, bound);
530      }
531  
# Line 584 | Line 534 | public class SplittableRandom {
534       * (inclusive) and one (exclusive).
535       *
536       * @return a pseudorandom {@code double} value between zero
537 <     * (inclusive) and one (exclusive)
537 >     *         (inclusive) and one (exclusive)
538       */
539      public double nextDouble() {
540 <        return (mix64(nextSeed()) >>> 11) * DOUBLE_UNIT;
540 >        return (mix64(nextSeed()) >>> 11) * DOUBLE_ULP;
541      }
542  
543      /**
544       * Returns a pseudorandom {@code double} value between 0.0
545       * (inclusive) and the specified bound (exclusive).
546       *
547 <     * @param bound the bound on the random number to be returned.  Must be
598 <     *        positive.
547 >     * @param bound the upper bound (exclusive).  Must be positive.
548       * @return a pseudorandom {@code double} value between zero
549       *         (inclusive) and the bound (exclusive)
550 <     * @throws IllegalArgumentException if {@code bound} is less than zero
550 >     * @throws IllegalArgumentException if {@code bound} is not positive
551       */
552      public double nextDouble(double bound) {
553          if (!(bound > 0.0))
554 <            throw new IllegalArgumentException("bound must be positive");
555 <        double result = (mix64(nextSeed()) >>> 11) * DOUBLE_UNIT * bound;
554 >            throw new IllegalArgumentException(BadBound);
555 >        double result = (mix64(nextSeed()) >>> 11) * DOUBLE_ULP * bound;
556          return (result < bound) ?  result : // correct for rounding
557              Double.longBitsToDouble(Double.doubleToLongBits(bound) - 1);
558      }
# Line 613 | Line 562 | public class SplittableRandom {
562       * origin (inclusive) and bound (exclusive).
563       *
564       * @param origin the least value returned
565 <     * @param bound the upper bound
565 >     * @param bound the upper bound (exclusive)
566       * @return a pseudorandom {@code double} value between the origin
567       *         (inclusive) and the bound (exclusive)
568       * @throws IllegalArgumentException if {@code origin} is greater than
# Line 621 | Line 570 | public class SplittableRandom {
570       */
571      public double nextDouble(double origin, double bound) {
572          if (!(origin < bound))
573 <            throw new IllegalArgumentException("bound must be greater than origin");
573 >            throw new IllegalArgumentException(BadRange);
574          return internalNextDouble(origin, bound);
575      }
576  
# Line 638 | Line 587 | public class SplittableRandom {
587      // maintenance purposes the small differences across forms.
588  
589      /**
590 <     * Returns a stream producing the given {@code streamSize} number of
591 <     * pseudorandom {@code int} values.
590 >     * Returns a stream producing the given {@code streamSize} number
591 >     * of pseudorandom {@code int} values from this generator and/or
592 >     * one split from it.
593       *
594       * @param streamSize the number of values to generate
595       * @return a stream of pseudorandom {@code int} values
# Line 648 | Line 598 | public class SplittableRandom {
598       */
599      public IntStream ints(long streamSize) {
600          if (streamSize < 0L)
601 <            throw new IllegalArgumentException("negative Stream size");
601 >            throw new IllegalArgumentException(BadSize);
602          return StreamSupport.intStream
603              (new RandomIntsSpliterator
604               (this, 0L, streamSize, Integer.MAX_VALUE, 0),
# Line 657 | Line 607 | public class SplittableRandom {
607  
608      /**
609       * Returns an effectively unlimited stream of pseudorandom {@code int}
610 <     * values.
610 >     * values from this generator and/or one split from it.
611       *
612       * @implNote This method is implemented to be equivalent to {@code
613       * ints(Long.MAX_VALUE)}.
# Line 672 | Line 622 | public class SplittableRandom {
622      }
623  
624      /**
625 <     * Returns a stream producing the given {@code streamSize} number of
626 <     * pseudorandom {@code int} values, each conforming to the given
627 <     * origin and bound.
625 >     * Returns a stream producing the given {@code streamSize} number
626 >     * of pseudorandom {@code int} values from this generator and/or one split
627 >     * from it; each value conforms to the given origin (inclusive) and bound
628 >     * (exclusive).
629       *
630       * @param streamSize the number of values to generate
631 <     * @param randomNumberOrigin the origin of each random value
632 <     * @param randomNumberBound the bound of each random value
631 >     * @param randomNumberOrigin the origin (inclusive) of each random value
632 >     * @param randomNumberBound the bound (exclusive) of each random value
633       * @return a stream of pseudorandom {@code int} values,
634 <     *         each with the given origin and bound
634 >     *         each with the given origin (inclusive) and bound (exclusive)
635       * @throws IllegalArgumentException if {@code streamSize} is
636       *         less than zero, or {@code randomNumberOrigin}
637       *         is greater than or equal to {@code randomNumberBound}
# Line 688 | Line 639 | public class SplittableRandom {
639      public IntStream ints(long streamSize, int randomNumberOrigin,
640                            int randomNumberBound) {
641          if (streamSize < 0L)
642 <            throw new IllegalArgumentException("negative Stream size");
642 >            throw new IllegalArgumentException(BadSize);
643          if (randomNumberOrigin >= randomNumberBound)
644 <            throw new IllegalArgumentException("bound must be greater than origin");
644 >            throw new IllegalArgumentException(BadRange);
645          return StreamSupport.intStream
646              (new RandomIntsSpliterator
647               (this, 0L, streamSize, randomNumberOrigin, randomNumberBound),
# Line 699 | Line 650 | public class SplittableRandom {
650  
651      /**
652       * Returns an effectively unlimited stream of pseudorandom {@code
653 <     * int} values, each conforming to the given origin and bound.
653 >     * int} values from this generator and/or one split from it; each value
654 >     * conforms to the given origin (inclusive) and bound (exclusive).
655       *
656       * @implNote This method is implemented to be equivalent to {@code
657       * ints(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
658       *
659 <     * @param randomNumberOrigin the origin of each random value
660 <     * @param randomNumberBound the bound of each random value
659 >     * @param randomNumberOrigin the origin (inclusive) of each random value
660 >     * @param randomNumberBound the bound (exclusive) of each random value
661       * @return a stream of pseudorandom {@code int} values,
662 <     *         each with the given origin and bound
662 >     *         each with the given origin (inclusive) and bound (exclusive)
663       * @throws IllegalArgumentException if {@code randomNumberOrigin}
664       *         is greater than or equal to {@code randomNumberBound}
665       */
666      public IntStream ints(int randomNumberOrigin, int randomNumberBound) {
667          if (randomNumberOrigin >= randomNumberBound)
668 <            throw new IllegalArgumentException("bound must be greater than origin");
668 >            throw new IllegalArgumentException(BadRange);
669          return StreamSupport.intStream
670              (new RandomIntsSpliterator
671               (this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
# Line 721 | Line 673 | public class SplittableRandom {
673      }
674  
675      /**
676 <     * Returns a stream producing the given {@code streamSize} number of
677 <     * pseudorandom {@code long} values.
676 >     * Returns a stream producing the given {@code streamSize} number
677 >     * of pseudorandom {@code long} values from this generator and/or
678 >     * one split from it.
679       *
680       * @param streamSize the number of values to generate
681       * @return a stream of pseudorandom {@code long} values
# Line 731 | Line 684 | public class SplittableRandom {
684       */
685      public LongStream longs(long streamSize) {
686          if (streamSize < 0L)
687 <            throw new IllegalArgumentException("negative Stream size");
687 >            throw new IllegalArgumentException(BadSize);
688          return StreamSupport.longStream
689              (new RandomLongsSpliterator
690               (this, 0L, streamSize, Long.MAX_VALUE, 0L),
# Line 739 | Line 692 | public class SplittableRandom {
692      }
693  
694      /**
695 <     * Returns an effectively unlimited stream of pseudorandom {@code long}
696 <     * values.
695 >     * Returns an effectively unlimited stream of pseudorandom {@code
696 >     * long} values from this generator and/or one split from it.
697       *
698       * @implNote This method is implemented to be equivalent to {@code
699       * longs(Long.MAX_VALUE)}.
# Line 756 | Line 709 | public class SplittableRandom {
709  
710      /**
711       * Returns a stream producing the given {@code streamSize} number of
712 <     * pseudorandom {@code long} values, each conforming to the
713 <     * given origin and bound.
712 >     * pseudorandom {@code long} values from this generator and/or one split
713 >     * from it; each value conforms to the given origin (inclusive) and bound
714 >     * (exclusive).
715       *
716       * @param streamSize the number of values to generate
717 <     * @param randomNumberOrigin the origin of each random value
718 <     * @param randomNumberBound the bound of each random value
717 >     * @param randomNumberOrigin the origin (inclusive) of each random value
718 >     * @param randomNumberBound the bound (exclusive) of each random value
719       * @return a stream of pseudorandom {@code long} values,
720 <     *         each with the given origin and bound
720 >     *         each with the given origin (inclusive) and bound (exclusive)
721       * @throws IllegalArgumentException if {@code streamSize} is
722       *         less than zero, or {@code randomNumberOrigin}
723       *         is greater than or equal to {@code randomNumberBound}
# Line 771 | Line 725 | public class SplittableRandom {
725      public LongStream longs(long streamSize, long randomNumberOrigin,
726                              long randomNumberBound) {
727          if (streamSize < 0L)
728 <            throw new IllegalArgumentException("negative Stream size");
728 >            throw new IllegalArgumentException(BadSize);
729          if (randomNumberOrigin >= randomNumberBound)
730 <            throw new IllegalArgumentException("bound must be greater than origin");
730 >            throw new IllegalArgumentException(BadRange);
731          return StreamSupport.longStream
732              (new RandomLongsSpliterator
733               (this, 0L, streamSize, randomNumberOrigin, randomNumberBound),
# Line 782 | Line 736 | public class SplittableRandom {
736  
737      /**
738       * Returns an effectively unlimited stream of pseudorandom {@code
739 <     * long} values, each conforming to the given origin and bound.
739 >     * long} values from this generator and/or one split from it; each value
740 >     * conforms to the given origin (inclusive) and bound (exclusive).
741       *
742       * @implNote This method is implemented to be equivalent to {@code
743       * longs(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
744       *
745 <     * @param randomNumberOrigin the origin of each random value
746 <     * @param randomNumberBound the bound of each random value
745 >     * @param randomNumberOrigin the origin (inclusive) of each random value
746 >     * @param randomNumberBound the bound (exclusive) of each random value
747       * @return a stream of pseudorandom {@code long} values,
748 <     *         each with the given origin and bound
748 >     *         each with the given origin (inclusive) and bound (exclusive)
749       * @throws IllegalArgumentException if {@code randomNumberOrigin}
750       *         is greater than or equal to {@code randomNumberBound}
751       */
752      public LongStream longs(long randomNumberOrigin, long randomNumberBound) {
753          if (randomNumberOrigin >= randomNumberBound)
754 <            throw new IllegalArgumentException("bound must be greater than origin");
754 >            throw new IllegalArgumentException(BadRange);
755          return StreamSupport.longStream
756              (new RandomLongsSpliterator
757               (this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
# Line 805 | Line 760 | public class SplittableRandom {
760  
761      /**
762       * Returns a stream producing the given {@code streamSize} number of
763 <     * pseudorandom {@code double} values, each between zero
764 <     * (inclusive) and one (exclusive).
763 >     * pseudorandom {@code double} values from this generator and/or one split
764 >     * from it; each value is between zero (inclusive) and one (exclusive).
765       *
766       * @param streamSize the number of values to generate
767       * @return a stream of {@code double} values
# Line 815 | Line 770 | public class SplittableRandom {
770       */
771      public DoubleStream doubles(long streamSize) {
772          if (streamSize < 0L)
773 <            throw new IllegalArgumentException("negative Stream size");
773 >            throw new IllegalArgumentException(BadSize);
774          return StreamSupport.doubleStream
775              (new RandomDoublesSpliterator
776               (this, 0L, streamSize, Double.MAX_VALUE, 0.0),
# Line 824 | Line 779 | public class SplittableRandom {
779  
780      /**
781       * Returns an effectively unlimited stream of pseudorandom {@code
782 <     * double} values, each between zero (inclusive) and one
783 <     * (exclusive).
782 >     * double} values from this generator and/or one split from it; each value
783 >     * is between zero (inclusive) and one (exclusive).
784       *
785       * @implNote This method is implemented to be equivalent to {@code
786       * doubles(Long.MAX_VALUE)}.
# Line 841 | Line 796 | public class SplittableRandom {
796  
797      /**
798       * Returns a stream producing the given {@code streamSize} number of
799 <     * pseudorandom {@code double} values, each conforming to the
800 <     * given origin and bound.
799 >     * pseudorandom {@code double} values from this generator and/or one split
800 >     * from it; each value conforms to the given origin (inclusive) and bound
801 >     * (exclusive).
802       *
803       * @param streamSize the number of values to generate
804 <     * @param randomNumberOrigin the origin of each random value
805 <     * @param randomNumberBound the bound of each random value
804 >     * @param randomNumberOrigin the origin (inclusive) of each random value
805 >     * @param randomNumberBound the bound (exclusive) of each random value
806       * @return a stream of pseudorandom {@code double} values,
807 <     * each with the given origin and bound
807 >     *         each with the given origin (inclusive) and bound (exclusive)
808       * @throws IllegalArgumentException if {@code streamSize} is
809 <     * less than zero
809 >     *         less than zero
810       * @throws IllegalArgumentException if {@code randomNumberOrigin}
811       *         is greater than or equal to {@code randomNumberBound}
812       */
813      public DoubleStream doubles(long streamSize, double randomNumberOrigin,
814                                  double randomNumberBound) {
815          if (streamSize < 0L)
816 <            throw new IllegalArgumentException("negative Stream size");
816 >            throw new IllegalArgumentException(BadSize);
817          if (!(randomNumberOrigin < randomNumberBound))
818 <            throw new IllegalArgumentException("bound must be greater than origin");
818 >            throw new IllegalArgumentException(BadRange);
819          return StreamSupport.doubleStream
820              (new RandomDoublesSpliterator
821               (this, 0L, streamSize, randomNumberOrigin, randomNumberBound),
# Line 868 | Line 824 | public class SplittableRandom {
824  
825      /**
826       * Returns an effectively unlimited stream of pseudorandom {@code
827 <     * double} values, each conforming to the given origin and bound.
827 >     * double} values from this generator and/or one split from it; each value
828 >     * conforms to the given origin (inclusive) and bound (exclusive).
829       *
830       * @implNote This method is implemented to be equivalent to {@code
831       * doubles(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
832       *
833 <     * @param randomNumberOrigin the origin of each random value
834 <     * @param randomNumberBound the bound of each random value
833 >     * @param randomNumberOrigin the origin (inclusive) of each random value
834 >     * @param randomNumberBound the bound (exclusive) of each random value
835       * @return a stream of pseudorandom {@code double} values,
836 <     * each with the given origin and bound
836 >     *         each with the given origin (inclusive) and bound (exclusive)
837       * @throws IllegalArgumentException if {@code randomNumberOrigin}
838       *         is greater than or equal to {@code randomNumberBound}
839       */
840      public DoubleStream doubles(double randomNumberOrigin, double randomNumberBound) {
841          if (!(randomNumberOrigin < randomNumberBound))
842 <            throw new IllegalArgumentException("bound must be greater than origin");
842 >            throw new IllegalArgumentException(BadRange);
843          return StreamSupport.doubleStream
844              (new RandomDoublesSpliterator
845               (this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
# Line 940 | Line 897 | public class SplittableRandom {
897              long i = index, f = fence;
898              if (i < f) {
899                  index = f;
900 +                SplittableRandom r = rng;
901                  int o = origin, b = bound;
902                  do {
903 <                    consumer.accept(rng.internalNextInt(o, b));
903 >                    consumer.accept(r.internalNextInt(o, b));
904                  } while (++i < f);
905              }
906          }
# Line 994 | Line 952 | public class SplittableRandom {
952              long i = index, f = fence;
953              if (i < f) {
954                  index = f;
955 +                SplittableRandom r = rng;
956                  long o = origin, b = bound;
957                  do {
958 <                    consumer.accept(rng.internalNextLong(o, b));
958 >                    consumer.accept(r.internalNextLong(o, b));
959                  } while (++i < f);
960              }
961          }
# Line 1049 | Line 1008 | public class SplittableRandom {
1008              long i = index, f = fence;
1009              if (i < f) {
1010                  index = f;
1011 +                SplittableRandom r = rng;
1012                  double o = origin, b = bound;
1013                  do {
1014 <                    consumer.accept(rng.internalNextDouble(o, b));
1014 >                    consumer.accept(r.internalNextDouble(o, b));
1015                  } while (++i < f);
1016              }
1017          }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines