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.13 by dl, Thu Jul 25 13:19:09 2013 UTC

# Line 25 | Line 25
25  
26   package java.util;
27  
28 + import java.security.SecureRandom;
29   import java.util.concurrent.atomic.AtomicLong;
30   import java.util.Spliterator;
31   import java.util.function.IntConsumer;
# Line 41 | Line 42 | import java.util.stream.DoubleStream;
42   * generate subtasks. Class 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 110 | Line 115 | public class SplittableRandom {
115       * are encountered; see method addGammaModGeorge. For this to
116       * work, initial gamma values must be at least 13.
117       *
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     *
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." It also appears to work to
125 <     * use instead any of the variants proposed by David Stafford at
126 <     * http://zimbry.blogspot.com/2011/09/better-bit-mixing-improving-on.html
127 <     * but these variants have not yet been tested as thoroughly
128 <     * in the context of the implementation of SplittableRandom.
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 result
142 <     * has its top 32 bits avalanched well, though not the bottom 32 bits.
143 <     * DieHarder tests show that it is adequate for generating one
144 <     * random int from the 64-bit result of nextSeed.
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
# Line 154 | Line 149 | public class SplittableRandom {
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 System.nanotime(),
153 <     * and update using another "genuinely random" constant
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
# Line 164 | Line 159 | public class SplittableRandom {
159       */
160  
161      /**
162 <     * The "genuinely random" value for producing new gamma values.
163 <     * The value is arbitrary, subject to the requirement that it be
164 <     * greater or equal to 13.
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 = 0xF2281E2DBA6606F3L;
172 >    private static final long GAMMA_GAMMA = 0x00aae38294f712aabL;
173  
174      /**
175 <     * The "genuinely random" seed update value for default constructors.
176 <     * The value is arbitrary, subject to the requirement that it be
177 <     * greater or equal to 13.
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.
178       */
179 <    private static final long DEFAULT_SEED_GAMMA = 0xBD24B73A95FB84D9L;
179 >    private static final long DEFAULT_SEED_GAMMA = 0x9e3779b97f4a7c15L;
180 >
181 >    /**
182 >     * The value 13 with 64bit sign bit set. Used in the signed
183 >     * comparison in addGammaModGeorge.
184 >     */
185 >    private static final long BOTTOM13 = 0x800000000000000DL;
186  
187      /**
188       * The least non-zero value returned by nextDouble(). This value
# Line 187 | Line 194 | public class SplittableRandom {
194       * The next seed for default constructors.
195       */
196      private static final AtomicLong defaultSeedGenerator =
197 <        new AtomicLong(System.nanoTime());
197 >        new AtomicLong(getInitialDefaultSeed());
198  
199      /**
200       * The seed, updated only via method nextSeed.
# Line 215 | Line 222 | public class SplittableRandom {
222       * George < 2^64; thus we need only a conditional, not a loop,
223       * to be sure of getting a representable value.
224       *
225 <     * @param s a seed value
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)
231       */
232      private static long addGammaModGeorge(long s, long g) {
233          long p = s + g;
234 <        if (Long.compareUnsigned(p, g) >= 0)
224 <            return p;
225 <        long q = p - 13L;
226 <        return (Long.compareUnsigned(p, 13L) >= 0) ? q : (q + g);
234 >        return (p >= s) ? p : ((p >= BOTTOM13) ? p  : p + g) - 13L;
235      }
236  
237      /**
# Line 250 | Line 258 | public class SplittableRandom {
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;
273 +    }
274 +
275 +    /**
276       * 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
# Line 260 | Line 283 | public class SplittableRandom {
283          this.seed = seed;
284          long s = splitSeed, g;
285          do { // ensure gamma >= 13, considered as an unsigned integer
286 <            s = addGammaModGeorge(s, GAMMA_GAMMA);
287 <            g = mix64(s);
288 <        } while (Long.compareUnsigned(g, 13L) < 0);
286 >            s += GAMMA_GAMMA;
287 >            if (s >= GAMMA_PRIME)
288 >                s -= GAMMA_PRIME;
289 >            g = mix57(s);
290 >        } while (g < 13L);
291          this.gamma = g;
292          this.nextSplit = s;
293      }
# Line 287 | Line 312 | public class SplittableRandom {
312          return mix64(newSeed);
313      }
314  
315 +    /**
316 +     * Returns an initial default seed.
317 +     */
318 +    private static long getInitialDefaultSeed() {
319 +        byte[] seedBytes = java.security.SecureRandom.getSeed(8);
320 +        long s = (long)(seedBytes[0]) & 0xffL;
321 +        for (int i = 1; i < 8; ++i)
322 +            s = (s << 8) | ((long)(seedBytes[i]) & 0xffL);
323 +        return s;
324 +    }
325 +
326      /*
327       * Internal versions of nextX methods used by streams, as well as
328       * the public nextX(origin, bound) methods.  These exist mainly to
# Line 362 | Line 398 | public class SplittableRandom {
398          int r = mix32(nextSeed());
399          if (origin < bound) {
400              int n = bound - origin, m = n - 1;
401 <            if ((n & m) == 0L)
401 >            if ((n & m) == 0)
402                  r = (r & m) + origin;
403              else if (n > 0) {
404                  for (int u = r >>> 1;
# Line 401 | Line 437 | public class SplittableRandom {
437      /**
438       * Creates a new SplittableRandom instance using the specified
439       * initial seed. SplittableRandom instances created with the same
440 <     * seed generate identical sequences of values.
440 >     * seed in the same program generate identical sequences of values.
441       *
442       * @param seed the initial seed
443       */
444      public SplittableRandom(long seed) {
445 <        this(seed, 0);
445 >        this(seed, 0L);
446      }
447  
448      /**
# Line 453 | Line 489 | public class SplittableRandom {
489       * @param bound the bound on the random number to be returned.  Must be
490       *        positive.
491       * @return a pseudorandom {@code int} value between zero
492 <     *         (inclusive) and the bound (exclusive).
492 >     *         (inclusive) and the bound (exclusive)
493       * @throws IllegalArgumentException if the bound is less than zero
494       */
495      public int nextInt(int bound) {
# Line 462 | Line 498 | public class SplittableRandom {
498          // Specialize internalNextInt for origin 0
499          int r = mix32(nextSeed());
500          int m = bound - 1;
501 <        if ((bound & m) == 0L) // power of two
501 >        if ((bound & m) == 0) // power of two
502              r &= m;
503          else { // reject over-represented candidates
504              for (int u = r >>> 1;
# Line 480 | Line 516 | public class SplittableRandom {
516       * @param origin the least value returned
517       * @param bound the upper bound (exclusive)
518       * @return a pseudorandom {@code int} value between the origin
519 <     *         (inclusive) and the bound (exclusive).
519 >     *         (inclusive) and the bound (exclusive)
520       * @throws IllegalArgumentException if {@code origin} is greater than
521       *         or equal to {@code bound}
522       */
# Line 506 | Line 542 | public class SplittableRandom {
542       * @param bound the bound on the random number to be returned.  Must be
543       *        positive.
544       * @return a pseudorandom {@code long} value between zero
545 <     *         (inclusive) and the bound (exclusive).
545 >     *         (inclusive) and the bound (exclusive)
546       * @throws IllegalArgumentException if {@code bound} is less than zero
547       */
548      public long nextLong(long bound) {
# Line 533 | Line 569 | public class SplittableRandom {
569       * @param origin the least value returned
570       * @param bound the upper bound (exclusive)
571       * @return a pseudorandom {@code long} value between the origin
572 <     *         (inclusive) and the bound (exclusive).
572 >     *         (inclusive) and the bound (exclusive)
573       * @throws IllegalArgumentException if {@code origin} is greater than
574       *         or equal to {@code bound}
575       */
# Line 551 | Line 587 | public class SplittableRandom {
587       * (inclusive) and one (exclusive)
588       */
589      public double nextDouble() {
590 <        return (nextLong() >>> 11) * DOUBLE_UNIT;
590 >        return (mix64(nextSeed()) >>> 11) * DOUBLE_UNIT;
591      }
592  
593      /**
# Line 561 | Line 597 | public class SplittableRandom {
597       * @param bound the bound on the random number to be returned.  Must be
598       *        positive.
599       * @return a pseudorandom {@code double} value between zero
600 <     *         (inclusive) and the bound (exclusive).
600 >     *         (inclusive) and the bound (exclusive)
601       * @throws IllegalArgumentException if {@code bound} is less than zero
602       */
603      public double nextDouble(double bound) {
604          if (!(bound > 0.0))
605              throw new IllegalArgumentException("bound must be positive");
606 <        double result = nextDouble() * bound;
606 >        double result = (mix64(nextSeed()) >>> 11) * DOUBLE_UNIT * bound;
607          return (result < bound) ?  result : // correct for rounding
608              Double.longBitsToDouble(Double.doubleToLongBits(bound) - 1);
609      }
# Line 579 | Line 615 | public class SplittableRandom {
615       * @param origin the least value returned
616       * @param bound the upper bound
617       * @return a pseudorandom {@code double} value between the origin
618 <     *         (inclusive) and the bound (exclusive).
618 >     *         (inclusive) and the bound (exclusive)
619       * @throws IllegalArgumentException if {@code origin} is greater than
620       *         or equal to {@code bound}
621       */
# Line 589 | Line 625 | public class SplittableRandom {
625          return internalNextDouble(origin, bound);
626      }
627  
628 +    /**
629 +     * Returns a pseudorandom {@code boolean} value.
630 +     *
631 +     * @return a pseudorandom {@code boolean} value
632 +     */
633 +    public boolean nextBoolean() {
634 +        return mix32(nextSeed()) < 0;
635 +    }
636 +
637      // stream methods, coded in a way intended to better isolate for
638      // maintenance purposes the small differences across forms.
639  
# Line 612 | Line 657 | public class SplittableRandom {
657  
658      /**
659       * Returns an effectively unlimited stream of pseudorandom {@code int}
660 <     * values
660 >     * values.
661       *
662       * @implNote This method is implemented to be equivalent to {@code
663       * ints(Long.MAX_VALUE)}.
# Line 635 | Line 680 | public class SplittableRandom {
680       * @param randomNumberOrigin the origin of each random value
681       * @param randomNumberBound the bound of each random value
682       * @return a stream of pseudorandom {@code int} values,
683 <     *         each with the given origin and bound.
683 >     *         each with the given origin and bound
684       * @throws IllegalArgumentException if {@code streamSize} is
685       *         less than zero, or {@code randomNumberOrigin}
686       *         is greater than or equal to {@code randomNumberBound}
# Line 662 | Line 707 | public class SplittableRandom {
707       * @param randomNumberOrigin the origin of each random value
708       * @param randomNumberBound the bound of each random value
709       * @return a stream of pseudorandom {@code int} values,
710 <     *         each with the given origin and bound.
710 >     *         each with the given origin and bound
711       * @throws IllegalArgumentException if {@code randomNumberOrigin}
712       *         is greater than or equal to {@code randomNumberBound}
713       */
# Line 718 | Line 763 | public class SplittableRandom {
763       * @param randomNumberOrigin the origin of each random value
764       * @param randomNumberBound the bound of each random value
765       * @return a stream of pseudorandom {@code long} values,
766 <     *         each with the given origin and bound.
766 >     *         each with the given origin and bound
767       * @throws IllegalArgumentException if {@code streamSize} is
768       *         less than zero, or {@code randomNumberOrigin}
769       *         is greater than or equal to {@code randomNumberBound}
# Line 745 | Line 790 | public class SplittableRandom {
790       * @param randomNumberOrigin the origin of each random value
791       * @param randomNumberBound the bound of each random value
792       * @return a stream of pseudorandom {@code long} values,
793 <     *         each with the given origin and bound.
793 >     *         each with the given origin and bound
794       * @throws IllegalArgumentException if {@code randomNumberOrigin}
795       *         is greater than or equal to {@code randomNumberBound}
796       */
# Line 803 | Line 848 | public class SplittableRandom {
848       * @param randomNumberOrigin the origin of each random value
849       * @param randomNumberBound the bound of each random value
850       * @return a stream of pseudorandom {@code double} values,
851 <     * each with the given origin and bound.
851 >     * each with the given origin and bound
852       * @throws IllegalArgumentException if {@code streamSize} is
853 <     * less than zero.
853 >     * less than zero
854       * @throws IllegalArgumentException if {@code randomNumberOrigin}
855       *         is greater than or equal to {@code randomNumberBound}
856       */
# Line 831 | Line 876 | public class SplittableRandom {
876       * @param randomNumberOrigin the origin of each random value
877       * @param randomNumberBound the bound of each random value
878       * @return a stream of pseudorandom {@code double} values,
879 <     * each with the given origin and bound.
879 >     * each with the given origin and bound
880       * @throws IllegalArgumentException if {@code randomNumberOrigin}
881       *         is greater than or equal to {@code randomNumberBound}
882       */
# Line 852 | Line 897 | public class SplittableRandom {
897       * approach. The long and double versions of this class are
898       * identical except for types.
899       */
900 <    static class RandomIntsSpliterator implements Spliterator.OfInt {
900 >    static final class RandomIntsSpliterator implements Spliterator.OfInt {
901          final SplittableRandom rng;
902          long index;
903          final long fence;
# Line 906 | Line 951 | public class SplittableRandom {
951      /**
952       * Spliterator for long streams.
953       */
954 <    static class RandomLongsSpliterator implements Spliterator.OfLong {
954 >    static final class RandomLongsSpliterator implements Spliterator.OfLong {
955          final SplittableRandom rng;
956          long index;
957          final long fence;
# Line 961 | Line 1006 | public class SplittableRandom {
1006      /**
1007       * Spliterator for double streams.
1008       */
1009 <    static class RandomDoublesSpliterator implements Spliterator.OfDouble {
1009 >    static final class RandomDoublesSpliterator implements Spliterator.OfDouble {
1010          final SplittableRandom rng;
1011          long index;
1012          final long fence;
# Line 1013 | Line 1058 | public class SplittableRandom {
1058      }
1059  
1060   }
1016

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines