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.11 by dl, Tue Jul 16 12:32:05 2013 UTC vs.
Revision 1.14 by dl, Mon Aug 5 13:58:02 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 114 | 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       *
117     * The value of gamma differs for each instance across a series of
118     * splits, and is generated using a slightly stripped-down variant
119     * of the same algorithm, but operating across calls to split(),
120     * not calls to nextSeed(): Each instance carries the state of
121     * this generator as nextSplit, and uses mix64(nextSplit) as its
122     * own gamma value. Computations of gammas themselves use a fixed
123     * constant as the second argument to the addGammaModGeorge
124     * function, GAMMA_GAMMA, a "genuinely random" number from a
125     * radioactive decay reading (obtained from
126     * http://www.fourmilab.ch/hotbits/) meeting the above range
127     * constraint. Using a fixed constant maintains the invariant that
128     * the value of gamma is the same for every instance that is at
129     * the same split-distance from their common root. (Note: there is
130     * nothing especially magic about obtaining this constant from a
131     * "truly random" physical source rather than just choosing one
132     * arbitrarily; using "hotbits" was merely an aesthetically pleasing
133     * choice.  In either case, good statistical behavior of the
134     * algorithm should be, and was, verified by using the DieHarder
135     * test suite.)
136     *
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 "Mix13" 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 158 | 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 a function of the
153 <     * current System time as seed, and update using another
154 <     * "genuinely random" constant DEFAULT_SEED_GAMMA. The default
155 <     * constructor uses GAMMA_GAMMA, not 0, for its splitSeed argument
156 <     * (addGammaModGeorge(0, GAMMA_GAMMA) == GAMMA_GAMMA) to reflect
157 <     * that each is split from this root generator, even though the
158 <     * root is not explicitly represented as a SplittableRandom.  When
168 <     * establishing the initial seed, we use both
169 <     * System.currentTimeMillis and System.nanoTime(), to avoid
170 <     * regularities that may occur if using either alone.
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 "genuinely random" value for producing new gamma values.
175 <     * The value is arbitrary, subject to the requirement that it be
176 <     * greater or equal to 13.
162 >     * The prime modulus for gamma values.
163       */
164 <    private static final long GAMMA_GAMMA = 0xF2281E2DBA6606F3L;
164 >    private static final long GAMMA_PRIME = (1L << 57) - 13L;
165  
166      /**
167 <     * The "genuinely random" seed update value for default constructors.
168 <     * The value is arbitrary, subject to the requirement that it be
169 <     * greater or equal to 13.
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 DEFAULT_SEED_GAMMA = 0xBD24B73A95FB84D9L;
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.
178 >     */
179 >    private static final long DEFAULT_SEED_GAMMA = 0x9e3779b97f4a7c15L;
180  
181      /**
182       * The value 13 with 64bit sign bit set. Used in the signed
# Line 200 | Line 194 | public class SplittableRandom {
194       * The next seed for default constructors.
195       */
196      private static final AtomicLong defaultSeedGenerator =
197 <        new AtomicLong(mix64(System.currentTimeMillis()) ^
204 <                       mix64(System.nanoTime()));
197 >        new AtomicLong(getInitialDefaultSeed());
198  
199      /**
200       * The seed, updated only via method nextSeed.
# Line 265 | 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 ^ (z >>> 30)) * 0xbf58476d1ce4e5b9L;
266 +        z &= 0x01FFFFFFFFFFFFFFL;
267 +        z = (z ^ (z >>> 27)) * 0x94d049bb133111ebL;
268 +        z &= 0x01FFFFFFFFFFFFFFL;
269 +        z ^= (z >>> 31);
270 +        return z;
271 +    }
272 +
273 +    /**
274       * Internal constructor used by all other constructors and by
275       * method split. Establishes the initial seed for this instance,
276       * and uses the given splitSeed to establish gamma, as well as the
# Line 275 | Line 281 | public class SplittableRandom {
281          this.seed = seed;
282          long s = splitSeed, g;
283          do { // ensure gamma >= 13, considered as an unsigned integer
284 <            s = addGammaModGeorge(s, GAMMA_GAMMA);
285 <            g = mix64(s);
286 <        } while (g >= 0L && g < 13L);
284 >            s += GAMMA_GAMMA;
285 >            if (s >= GAMMA_PRIME)
286 >                s -= GAMMA_PRIME;
287 >            g = mix57(s);
288 >        } while (g < 13L);
289          this.gamma = g;
290          this.nextSplit = s;
291      }
# Line 302 | Line 310 | public class SplittableRandom {
310          return mix64(newSeed);
311      }
312  
313 +    /**
314 +     * Returns an initial default seed.
315 +     */
316 +    private static long getInitialDefaultSeed() {
317 +        byte[] seedBytes = java.security.SecureRandom.getSeed(8);
318 +        long s = (long)(seedBytes[0]) & 0xffL;
319 +        for (int i = 1; i < 8; ++i)
320 +            s = (s << 8) | ((long)(seedBytes[i]) & 0xffL);
321 +        return s;
322 +    }
323 +
324      /*
325       * Internal versions of nextX methods used by streams, as well as
326       * the public nextX(origin, bound) methods.  These exist mainly to
# Line 377 | Line 396 | public class SplittableRandom {
396          int r = mix32(nextSeed());
397          if (origin < bound) {
398              int n = bound - origin, m = n - 1;
399 <            if ((n & m) == 0L)
399 >            if ((n & m) == 0)
400                  r = (r & m) + origin;
401              else if (n > 0) {
402                  for (int u = r >>> 1;
# Line 421 | Line 440 | public class SplittableRandom {
440       * @param seed the initial seed
441       */
442      public SplittableRandom(long seed) {
443 <        this(seed, 0);
443 >        this(seed, 0L);
444      }
445  
446      /**
# Line 477 | Line 496 | public class SplittableRandom {
496          // Specialize internalNextInt for origin 0
497          int r = mix32(nextSeed());
498          int m = bound - 1;
499 <        if ((bound & m) == 0L) // power of two
499 >        if ((bound & m) == 0) // power of two
500              r &= m;
501          else { // reject over-represented candidates
502              for (int u = r >>> 1;

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines