# HG changeset patch # User briangoetz # Date 1558644356 14400 # Node ID 6d87e9f7a1ec162349347dbc3d0723302f17e23f # Parent c646b256fbcc03124848767b6a7610cd61b9c664 Initial comment in newrandom/ diff -r c646b256fbcc -r 6d87e9f7a1ec newrandom/AbstractArbitrarilyJumpableRng.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/newrandom/AbstractArbitrarilyJumpableRng.java Thu May 23 16:45:56 2019 -0400 @@ -0,0 +1,543 @@ +/* + * Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. + * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + */ + +// package java.util; + +import java.util.Spliterator; +import java.util.function.Consumer; +import java.util.function.IntConsumer; +import java.util.function.LongConsumer; +import java.util.function.DoubleConsumer; +import java.util.stream.StreamSupport; +import java.util.stream.Stream; + +/** + * This class provides much of the implementation of the + * {@code ArbitrarilyJumpableRng} interface, to minimize the effort + * required to implement that interface. + * + * To implement a pseudorandom number generator, the programmer needs + * only to extend this class and provide implementations for the + * methods {@code nextInt()}, {@code nextLong()}, {@code copy()}, + * {@code jump(distance)}, {@code jumpPowerOfTwo(distance)}, + * {@code defaultJumpDistance()}, and {@code defaultLeapDistance()}. + * + * (If the pseudorandom number generator also has the ability to split, + * then the programmer may wish to consider instead extending + * {@code AbstractSplittableArbitrarilyJumpableRng}.) + * + * The programmer should generally provide at least three constructors: + * one that takes no arguments, one that accepts a {@code long} + * seed value, and one that accepts an array of seed {@code byte} values. + * This class provides a public {@code initialSeed()} method that may + * be useful in initializing some static state from which to derive + * defaults seeds for use by the no-argument constructor. + * + * For the stream methods (such as {@code ints()} and {@code splits()}), + * this class provides {@code Spliterator}-based implementations that + * allow parallel execution when appropriate. In this respect + * {@code ArbitrarilyJumpableRng} differs from {@code JumpableRng}, + * which provides very simple implementations that produce + * sequential streams only. + * + *
An implementation of the {@code AbstractArbitrarilyJumpableRng} class
+ * must provide concrete definitions for the methods {@code nextInt()},
+ * {@code nextLong}, {@code period()}, {@code copy()}, {@code jump(double)},
+ * {@code defaultJumpDistance()}, and {@code defaultLeapDistance()}.
+ * Default implementations are provided for all other methods.
+ *
+ * The documentation for each non-abstract method in this class
+ * describes its implementation in detail. Each of these methods may
+ * be overridden if the pseudorandom number generator being
+ * implemented admits a more efficient implementation.
+ *
+ * @author Guy Steele
+ * @since 1.9
+ */
+public abstract class AbstractArbitrarilyJumpableRng
+ extends AbstractSpliteratorRng implements ArbitrarilyJumpableRng {
+
+ /*
+ * Implementation Overview.
+ *
+ * This class provides most of the "user API" methods needed to satisfy
+ * the interface java.util.ArbitrarilyJumpableRng. Most of these methods
+ * are in turn inherited from AbstractRng and the non-public class
+ * AbstractSpliteratorRng; this file implements four versions of the
+ * jumps method and defines the spliterators necessary to support them.
+ *
+ * File organization: First the non-public methods needed by the class
+ * AbstractSpliteratorRng, then the main public methods, followed by some
+ * custom spliterator classes needed for stream methods.
+ */
+
+ // IllegalArgumentException messages
+ static final String BadLogDistance = "logDistance must be non-negative";
+
+ // Methods required by class AbstractSpliteratorRng
+ Spliterator.OfInt makeIntsSpliterator(long index, long fence, int origin, int bound) {
+ return new RandomIntsSpliterator(this, index, fence, origin, bound);
+ }
+ Spliterator.OfLong makeLongsSpliterator(long index, long fence, long origin, long bound) {
+ return new RandomLongsSpliterator(this, index, fence, origin, bound);
+ }
+ Spliterator.OfDouble makeDoublesSpliterator(long index, long fence, double origin, double bound) {
+ return new RandomDoublesSpliterator(this, index, fence, origin, bound);
+ }
+
+ // Similar methods used by this class
+ Spliterator Ideally, all {@code ArbitrarilyJumpableRng} objects produced by
+ * iterative jumping from a single original {@code ArbtrarilyJumpableRng}
+ * object are statistically independent of one another and
+ * individually uniform, provided that they do not traverse
+ * overlapping portions of the state cycle. In practice, one must
+ * settle for some approximation to independence and uniformity. In
+ * particular, a specific implementation may assume that each
+ * generator in a stream produced by the {@code jumps} method is used
+ * to produce a number of values no larger than the jump distance
+ * specified. Implementors are advised to use algorithms whose period
+ * is at least 2127.
+ *
+ * For many applications, it suffices to jump forward by a power of
+ * two or some small multiple of a power of two, but this power of two
+ * may not be representable as a {@code long} value. To avoid the
+ * use of {@code BigInteger} values as jump distances, {@code double}
+ * values are used instead.
+ *
+ * Methods are provided to perform a single jump operation and also
+ * to produce a stream of generators produced from the original by
+ * iterative copying and jumping of internal state. A typical
+ * strategy for a multithreaded application is to create a single
+ * {@code ArbitrarilyJumpableRng} object, call its {@code jumps}
+ * method exactly once, and then parcel out generators from the
+ * resulting stream, one to each thread. However, each generator
+ * produced also has type {@code ArbitrarilyJumpableRng}; with care,
+ * different jump distances can be used to traverse the entire
+ * state cycle in various ways.
+ *
+ * An implementation of the {@code ArbitrarilyJumpableRng} interface must
+ * provide concrete definitions for the methods {@code nextInt()},
+ * {@code nextLong}, {@code period()}, {@code copy()}, {@code jump(double)},
+ * {@code defaultJumpDistance()}, and {@code defaultLeapDistance()}.
+ * Default implementations are provided for all other methods.
+ * Perhaps the most convenient
+ * way to implement this interface is to extend the abstract class
+ * {@link java.util.AbstractArbitrarilyJumpableRng}, which provides
+ * spliterator-based implementations of the methods {@code ints}, {@code longs},
+ * {@code doubles}, {@code rngs}, {@code jumps}, and {@code leaps}.
+ *
+ * Objects that implement {@code java.util.ArbitrarilyJumpableRng}
+ * are typically not cryptographically secure. Consider instead using
+ * {@link java.security.SecureRandom} to get a cryptographically
+ * secure pseudo-random number generator for use by
+ * security-sensitive applications.
+ *
+ * @author Guy Steele
+ * @since 1.9
+ */
+interface ArbitrarilyJumpableRng extends LeapableRng {
+ /**
+ * Returns a new generator whose internal state is an exact copy
+ * of this generator (therefore their future behavior should be
+ * identical if subjected to the same series of operations).
+ *
+ * @return a new object that is a copy of this generator
+ */
+ ArbitrarilyJumpableRng copy();
+
+ /**
+ * Alter the state of this pseudorandom number generator so as to
+ * jump forward a distance equal to 2{@code logDistance}
+ * within its state cycle.
+ *
+ * @param logDistance the base-2 logarithm of the distance to jump
+ * forward within the state cycle
+ * @throws IllegalArgumentException if {@code logDistance} is NaN
+ * or negative, or if 2{@code logDistance} is
+ * greater than the period of this generator
+ */
+ void jumpPowerOfTwo(int logDistance);
+
+ /**
+ * Alter the state of this pseudorandom number generator so as to
+ * jump forward a specified distance within its state cycle.
+ *
+ * @param distance the distance to jump forward within the state cycle
+ * @throws IllegalArgumentException if {@code distance} is Nan,
+ * negative, or greater than the period of this generator
+ */
+ void jump(double distance);
+
+ /**
+ * Alter the state of this pseudorandom number generator so as to
+ * jump forward a large, fixed distance (typically 264
+ * or more) within its state cycle. The distance used is that
+ * returned by method {@code defaultJumpDistance()}.
+ */
+ default void jump() { jump(defaultJumpDistance()); }
+
+ /**
+ * Returns an effectively unlimited stream of new pseudorandom
+ * number generators, each of which implements the {@code ArbitrarilyJumpableRng}
+ * interface, produced by jumping copies of this generator
+ * by different integer multiples of the specified jump distance.
+ *
+ * @implNote This method is implemented to be equivalent to
+ * {@code jumps(Long.MAX_VALUE)}.
+ *
+ * @param distance a distance to jump forward within the state cycle
+ * @return a stream of objects that implement the {@code Rng} interface
+ */
+ default Stream Ideally, all {@code JumpableRng} objects produced by iterative
+ * jumping from a single original {@code JumpableRng} object are
+ * statistically independent of one another and individually uniform.
+ * In practice, one must settle for some approximation to independence
+ * and uniformity. In particular, a specific implementation may
+ * assume that each generator in a stream produced by the {@code jumps}
+ * method is used to produce a number of values no larger than either
+ * 264 or the square root of its period. Implementors are
+ * advised to use algorithms whose period is at least 2127.
+ *
+ * Methods are provided to perform a single jump operation and also
+ * to produce a stream of generators produced from the original by
+ * iterative copying and jumping of internal state. A typical
+ * strategy for a multithreaded application is to create a single
+ * {@code JumpableRng} object, calls its {@code jumps} method exactly
+ * once, and then parcel out generators from the resulting stream, one
+ * to each thread. It is generally not a good idea to call {@code jump}
+ * on a generator that was itself produced by the {@code jumps} method,
+ * because the result may be a generator identical to another
+ * generator already produce by that call to the {@code jumps} method.
+ * For this reason, the return type of the {@code jumps} method is
+ * {@code Stream An implementation of the {@code JumpableRng} interface must provide
+ * concrete definitions for the methods {@code nextInt()}, {@code nextLong},
+ * {@code period()}, {@code copy()}, {@code jump()}, and {@code defaultJumpDistance()}.
+ * Default implementations are provided for all other methods.
+ *
+ * Objects that implement {@code java.util.JumpableRng} are
+ * typically not cryptographically secure. Consider instead using
+ * {@link java.security.SecureRandom} to get a cryptographically
+ * secure pseudo-random number generator for use by
+ * security-sensitive applications.
+ *
+ * @author Guy Steele
+ * @since 1.9
+ */
+interface JumpableRng extends StreamableRng {
+ /**
+ * Returns a new generator whose internal state is an exact copy
+ * of this generator (therefore their future behavior should be
+ * identical if subjected to the same series of operations).
+ *
+ * @return a new object that is a copy of this generator
+ */
+ JumpableRng copy();
+
+ /**
+ * Alter the state of this pseudorandom number generator so as to
+ * jump forward a large, fixed distance (typically 264
+ * or more) within its state cycle.
+ */
+ void jump();
+
+ /**
+ * Returns the distance by which the {@code jump()} method will jump
+ * forward within the state cycle of this generator object.
+ *
+ * @return the default jump distance (as a {@code double} value)
+ */
+ double defaultJumpDistance();
+
+ /**
+ * Returns an effectively unlimited stream of new pseudorandom
+ * number generators, each of which implements the {@code Rng}
+ * interface.
+ *
+ * @implNote It is permitted to implement this method in a manner
+ * equivalent to {@code jumps(Long.MAX_VALUE)}.
+ *
+ * @implNote The default implementation produces a sequential stream
+ * that repeatedly calls {@code copy()} and {@code jump()} on this generator,
+ * and the copies become the generators produced by the stream.
+ *
+ * @return a stream of objects that implement the {@code Rng} interface
+ */
+ default Stream Series of generated values pass the TestU01 BigCrush and PractRand test suites
+ * that measure independence and uniformity properties of random number generators.
+ * (Most recently validated with
+ * version 1.2.3 of TestU01
+ * and version 0.90 of PractRand.
+ * Note that TestU01 BigCrush was used to test not only values produced by the {@code nextLong()}
+ * method but also the result of bit-reversing each value produced by {@code nextLong()}.)
+ * These tests validate only the methods for certain
+ * types and ranges, but similar properties are expected to hold, at
+ * least approximately, for others as well.
+ *
+ * {@code L128X256MixRandom} is a specific member of the LXM family of algorithms
+ * for pseudorandom number generators. Every LXM generator consists of two
+ * subgenerators; one is an LCG (Linear Congruential Generator) and the other is
+ * an Xorshift generator. Each output of an LXM generator is the sum of one
+ * output from each subgenerator, possibly processed by a final mixing function
+ * (and {@code L128X256MixRandom} does use a mixing function).
+ *
+ * The LCG subgenerator for {@code L128X256MixRandom} has an update step of the
+ * form {@code s = m * s + a}, where {@code s}, {@code m}, and {@code a} are all
+ * 128-bit integers; {@code s} is the mutable state, the multiplier {@code m}
+ * is fixed (the same for all instances of {@code L128X256MixRandom}}) and the addend
+ * {@code a} is a parameter (a final field of the instance). The parameter
+ * {@code a} is required to be odd (this allows the LCG to have the maximal
+ * period, namely 2128); therefore there are 2127 distinct choices
+ * of parameter.
+ *
+ * The Xorshift subgenerator for {@code L128X256MixRandom} is the {@code xoshiro256} algorithm,
+ * version 1.0 (parameters 17, 45), without any final scrambler such as "+" or "**".
+ * Its state consists of four {@code long} fields {@code x0}, {@code x1}, {@code x2},
+ * and {@code x3}, which can take on any values provided that they are not all zero.
+ * The period of this subgenerator is 2256-1.
+ *
+ * The mixing function for {@code L128X256MixRandom} is the 64-bit MurmurHash3 finalizer.
+ *
+ * Because the periods 2128 and 2256-1 of the two subgenerators
+ * are relatively prime, the period of any single {@code L128X256MixRandom} object
+ * (the length of the series of generated 64-bit values before it repeats) is the product
+ * of the periods of the subgenerators, that is, 2128(2256-1),
+ * which is just slightly smaller than 2384. Moreover, if two distinct
+ * {@code L128X256MixRandom} objects have different {@code a} parameters, then their
+ * cycles of produced values will be different.
+ *
+ * The 64-bit values produced by the {@code nextLong()} method are exactly equidistributed.
+ * For any specific instance of {@code L128X256MixRandom}, over the course of its cycle each
+ * of the 264 possible {@code long} values will be produced 2256-1 times.
+ * The values produced by the {@code nextInt()}, {@code nextFloat()}, and {@code nextDouble()}
+ * methods are likewise exactly equidistributed.
+ *
+ * In fact, the 64-bit values produced by the {@code nextLong()} method are exactly
+ * 2-equidistributed. For any specific instance of {@code L128X256MixRandom}, consider
+ * the (overlapping) length-2 subsequences of the cycle of 64-bit values produced by
+ * {@code nextLong()} (assuming no other methods are called that would affect the state).
+ * There are 2128(2256-1) such subsequences, and each subsequence,
+ * which consists of 2 64-bit values, can have one of 2128 values, and each
+ * such value occurs 2256-1 times. The values produced by the {@code nextInt()},
+ * {@code nextFloat()}, and {@code nextDouble()} methods are likewise exactly 2-equidistributed.
+ *
+ * Moreover, the 64-bit values produced by the {@code nextLong()} method are 4-equidistributed.
+ * To be precise: for any specific instance of {@code L128X256MixRandom}, consider
+ * the (overlapping) length-4 subsequences of the cycle of 64-bit values produced by
+ * {@code nextLong()} (assuming no other methods are called that would affect the state).
+ * There are 128(2256-1) such subsequences, and each subsequence,
+ * which consists of 4 64-bit values, can have one of 2256 values. Of those
+ * 2256 subsequence values, nearly all of them (2256-2128)
+ * occur 2128 times over the course of the entire cycle, and the other
+ * 2128 subsequence values occur only 2128-1 times. So the ratio
+ * of the probability of getting one of the less common subsequence values and the
+ * probability of getting one of the more common subsequence values is 1-2-128.
+ * (Note that the set of 2128 less-common subsequence values will differ from
+ * one instance of {@code L128X256MixRandom} to another, as a function of the additive
+ * parameter of the LCG.) The values produced by the {@code nextInt()}, {@code nextFloat()},
+ * and {@code nextDouble()} methods are likewise 4-equidistributed.
+ *
+ * Method {@link #split} constructs and returns a new {@code L128X256MixRandom}
+ * instance that shares no mutable state with the current instance. However, with
+ * very high probability, the values collectively generated by the two objects
+ * have the same statistical properties as if the same quantity of values were
+ * generated by a single thread using a single {@code L128X256MixRandom} object.
+ * This is because, with high probability, distinct {@code L128X256MixRandom} objects
+ * have distinct {@code a} parameters and therefore use distinct members of the
+ * algorithmic family; and even if their {@code a} parameters are the same, with
+ * very high probability they will traverse different parts of their common state
+ * cycle.
+ *
+ * As with {@link java.util.SplittableRandom}, instances of
+ * {@code L128X256MixRandom} are not thread-safe.
+ * They are designed to be split, not shared, across threads. For
+ * example, a {@link java.util.concurrent.ForkJoinTask} fork/join-style
+ * computation using random numbers might include a construction
+ * of the form {@code new Subtask(someL128X256MixRandom.split()).fork()}.
+ *
+ * This class provides additional methods for generating random
+ * streams, that employ the above techniques when used in
+ * {@code stream.parallel()} mode.
+ *
+ * Instances of {@code L128X256MixRandom} are not cryptographically
+ * secure. Consider instead using {@link java.security.SecureRandom}
+ * in security-sensitive applications. Additionally,
+ * default-constructed instances do not use a cryptographically random
+ * seed unless the {@linkplain System#getProperty system property}
+ * {@code java.util.secureRandomSeed} is set to {@code true}.
+ *
+ * @author Guy Steele
+ * @since 1.9
+ */
+public final class L128X256MixRandom extends AbstractSplittableRng {
+
+ /*
+ * Implementation Overview.
+ *
+ * The 128-bit parameter `a` is represented as two long fields `ah` and `al`.
+ * The 128-bit state variable `s` is represented as two long fields `sh` and `sl`.
+ *
+ * The split operation uses the current generator to choose eight
+ * new 64-bit long values that are then used to initialize the
+ * parameters `ah` and `al` and the state variables `sh`, `sl`,
+ * `x0`, `x1`, `x2`, and `x3` for a newly constructed generator.
+ *
+ * With extremely high probability, no two generators so chosen
+ * will have the same `a` parameter, and testing has indicated
+ * that the values generated by two instances of {@code L128X256MixRandom}
+ * will be (approximately) independent if have different values for `a`.
+ *
+ * The default (no-argument) constructor, in essence, uses
+ * "defaultGen" to generate eight new 64-bit values for the same
+ * purpose. Multiple generators created in this way will certainly
+ * differ in their `a` parameters. The defaultGen state must be accessed
+ * in a thread-safe manner, so we use an AtomicLong to represent
+ * this state. To bootstrap the defaultGen, we start off using a
+ * seed based on current time unless the
+ * java.util.secureRandomSeed property is set. This serves as a
+ * slimmed-down (and insecure) variant of SecureRandom that also
+ * avoids stalls that may occur when using /dev/random.
+ *
+ * File organization: First static fields, then instance
+ * fields, then constructors, then instance methods.
+ */
+
+ /* ---------------- static fields ---------------- */
+
+ /**
+ * The seed generator for default constructors.
+ */
+ private static final AtomicLong defaultGen = new AtomicLong(RngSupport.initialSeed());
+
+ /*
+ * The period of this generator, which is (2**256 - 1) * 2**128.
+ */
+ private static final BigInteger thePeriod =
+ BigInteger.ONE.shiftLeft(256).subtract(BigInteger.ONE).shiftLeft(128);
+
+ /*
+ * The multiplier used in the LCG portion of the algorithm is 2**64 + m;
+ * where m is taken from
+ * Pierre L'Ecuyer, Tables of linear congruential generators of
+ * different sizes and good lattice structure, Mathematics of
+ * Computation 68, 225 (January 1999), pages 249–260,
+ * Table 4 (first multiplier for size 264).
+ *
+ * This is almost certainly not the best possible 128-bit multiplier
+ * for an LCG, but it is sufficient for our purposes here; because
+ * is is larger than 2**64, the 64-bit values produced by nextLong()
+ * are exactly 2-equidistributed, and the fact that it is of the
+ * form (2**64 + m) simplifies the code, given that we have only
+ * 64-bit arithmetic to work with.
+ */
+
+ private static final long m = 2862933555777941757L;
+
+ /* ---------------- instance fields ---------------- */
+
+ /**
+ * The parameter that is used as an additive constant for the LCG.
+ * Must be odd.
+ */
+ private final long ah, al;
+
+ /**
+ * The per-instance state: sh and sl for the LCG; x0, x1, x2, and x3 for the xorshift.
+ * At least one of the four fields x0, x1, x2, and x3 must be nonzero.
+ */
+ private long sh, sl, x0, x1, x2, x3;
+
+ /* ---------------- constructors ---------------- */
+
+ /**
+ * Basic constructor that initializes all fields from parameters.
+ * It then adjusts the field values if necessary to ensure that
+ * all constraints on the values of fields are met.
+ */
+ public L128X256MixRandom(long ah, long al, long sh, long sl, long x0, long x1, long x2, long x3) {
+ // Force a to be odd.
+ this.ah = ah;
+ this.al = al | 1;
+ this.sh = sh;
+ this.sl = sl;
+ this.x0 = x0;
+ this.x1 = x1;
+ this.x2 = x2;
+ this.x3 = x3;
+ // If x0, x1, x2, and x3 are all zero, we must choose nonzero values.
+ if ((x0 | x1 | x2 | x3) == 0) {
+ // At least three of the four values generated here will be nonzero.
+ this.x0 = RngSupport.mixStafford13(sh += RngSupport.GOLDEN_RATIO_64);
+ this.x1 = RngSupport.mixStafford13(sh += RngSupport.GOLDEN_RATIO_64);
+ this.x2 = RngSupport.mixStafford13(sh += RngSupport.GOLDEN_RATIO_64);
+ this.x3 = RngSupport.mixStafford13(sh + RngSupport.GOLDEN_RATIO_64);
+ }
+ }
+
+ /**
+ * Creates a new instance of {@code L128X256MixRandom} using the
+ * specified {@code long} value as the initial seed. Instances of
+ * {@code L128X256MixRandom} created with the same seed in the same
+ * program generate identical sequences of values.
+ *
+ * @param seed the initial seed
+ */
+ public L128X256MixRandom(long seed) {
+ // Using a value with irregularly spaced 1-bits to xor the seed
+ // argument tends to improve "pedestrian" seeds such as 0 or
+ // other small integers. We may as well use SILVER_RATIO_64.
+ //
+ // The seed is hashed by mixMurmur64 to produce the `a` parameter.
+ // The seed is hashed by mixStafford13 to produce the initial `x0`,
+ // which will then be used to produce the first generated value.
+ // The other x values are filled in as if by a SplitMix PRNG with
+ // GOLDEN_RATIO_64 as the gamma value and Stafford13 as the mixer.
+ this(RngSupport.mixMurmur64(seed ^= RngSupport.SILVER_RATIO_64),
+ RngSupport.mixMurmur64(seed += RngSupport.GOLDEN_RATIO_64),
+ 0,
+ 1,
+ RngSupport.mixStafford13(seed),
+ RngSupport.mixStafford13(seed += RngSupport.GOLDEN_RATIO_64),
+ RngSupport.mixStafford13(seed += RngSupport.GOLDEN_RATIO_64),
+ RngSupport.mixStafford13(seed + RngSupport.GOLDEN_RATIO_64));
+ }
+
+ /**
+ * Creates a new instance of {@code L128X256MixRandom} that is likely to
+ * generate sequences of values that are statistically independent
+ * of those of any other instances in the current program execution,
+ * but may, and typically does, vary across program invocations.
+ */
+ public L128X256MixRandom() {
+ // Using GOLDEN_RATIO_64 here gives us a good Weyl sequence of values.
+ this(defaultGen.getAndAdd(RngSupport.GOLDEN_RATIO_64));
+ }
+
+ /**
+ * Creates a new instance of {@code L128X256MixRandom} using the specified array of
+ * initial seed bytes. Instances of {@code L128X256MixRandom} created with the same
+ * seed array in the same program execution generate identical sequences of values.
+ *
+ * @param seed the initial seed
+ */
+ public L128X256MixRandom(byte[] seed) {
+ // Convert the seed to 6 long values, of which the last 4 are not all zero.
+ long[] data = RngSupport.convertSeedBytesToLongs(seed, 6, 4);
+ long ah = data[0], al = data[1], sh = data[2], sl = data[3], x0 = data[4], x1 = data[5], x2 = data[6], x3 = data[7];
+ // Force a to be odd.
+ this.ah = ah;
+ this.al = al | 1;
+ this.sh = sh;
+ this.sl = sl;
+ this.x0 = x0;
+ this.x1 = x1;
+ this.x2 = x2;
+ this.x3 = x3;
+ }
+
+ /* ---------------- public methods ---------------- */
+
+ /**
+ * Constructs and returns a new instance of {@code L128X256MixRandom}
+ * that shares no mutable state with this instance.
+ * However, with very high probability, the set of values collectively
+ * generated by the two objects has the same statistical properties as if
+ * same the quantity of values were generated by a single thread using
+ * a single {@code L128X256MixRandom} object. Either or both of the two
+ * objects may be further split using the {@code split} method,
+ * and the same expected statistical properties apply to the
+ * entire set of generators constructed by such recursive splitting.
+ *
+ * @param source a {@code SplittableRng} instance to be used instead
+ * of this one as a source of pseudorandom bits used to
+ * initialize the state of the new ones.
+ * @return a new instance of {@code L128X256MixRandom}
+ */
+ public L128X256MixRandom split(SplittableRng source) {
+ // Literally pick a new instance "at random".
+ return new L128X256MixRandom(source.nextLong(), source.nextLong(),
+ source.nextLong(), source.nextLong(),
+ source.nextLong(), source.nextLong(),
+ source.nextLong(), source.nextLong());
+ }
+
+ /**
+ * Returns a pseudorandom {@code long} value.
+ *
+ * @return a pseudorandom {@code long} value
+ */
+
+ public long nextLong() {
+ final long z = sh + x0;
+ // The LCG: in effect, s = ((1LL << 64) + m) * s + a, if only we had 128-bit arithmetic.
+ final long u = m * sl;
+ sh = (m * sh) + Math.multiplyHigh(m, sl) + sl + ah;
+ sl = u + al;
+ if (Long.compareUnsigned(sl, u) < 0) ++sh; // Handle the carry propagation from low half to high half.
+ long q0 = x0, q1 = x1, q2 = x2, q3 = x3;
+ { long t = q1 << 17; q2 ^= q0; q3 ^= q1; q1 ^= q2; q0 ^= q3; q2 ^= t; q3 = Long.rotateLeft(q3, 45); } // xoshiro256 1.0
+ x0 = q0; x1 = q1; x2 = q2; x3 = q3;
+ return RngSupport.mixLea64(z); // mixing function
+ }
+
+ public BigInteger period() { return thePeriod; }
+}
diff -r c646b256fbcc -r 6d87e9f7a1ec newrandom/L32X64MixRandom.java
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/newrandom/L32X64MixRandom.java Thu May 23 16:45:56 2019 -0400
@@ -0,0 +1,325 @@
+/*
+ * Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
+ * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ */
+
+// package java.util;
+
+import java.math.BigInteger;
+import java.util.concurrent.atomic.AtomicLong;
+
+/**
+ * A generator of uniform pseudorandom values applicable for use in
+ * (among other contexts) isolated parallel computations that may
+ * generate subtasks. Class {@code L32X64MixRandom} implements
+ * interfaces {@link java.util.Rng} and {@link java.util.SplittableRng},
+ * and therefore supports methods for producing pseudorandomly chosen
+ * numbers of type {@code int}, {@code long}, {@code float}, and {@code double}
+ * as well as creating new split-off {@code L32X64MixRandom} objects,
+ * with similar usages as for class {@link java.util.SplittableRandom}.
+ *
+ * Series of generated values pass the TestU01 BigCrush and PractRand test suites
+ * that measure independence and uniformity properties of random number generators.
+ * (Most recently validated with
+ * version 1.2.3 of TestU01
+ * and version 0.90 of PractRand.
+ * Note that TestU01 BigCrush was used to test not only values produced by the {@code nextLong()}
+ * method but also the result of bit-reversing each value produced by {@code nextLong()}.)
+ * These tests validate only the methods for certain
+ * types and ranges, but similar properties are expected to hold, at
+ * least approximately, for others as well.
+ *
+ * {@code L32X64MixRandom} is a specific member of the LXM family of algorithms
+ * for pseudorandom number generators. Every LXM generator consists of two
+ * subgenerators; one is an LCG (Linear Congruential Generator) and the other is
+ * an Xorshift generator. Each output of an LXM generator is the sum of one
+ * output from each subgenerator, possibly processed by a final mixing function
+ * (and {@code L32X64MixRandom} does use a mixing function).
+ *
+ * The LCG subgenerator for {@code L32X64MixRandom} has an update step of the
+ * form {@code s = m * s + a}, where {@code s}, {@code m}, and {@code a} are all
+ * of type {@code int}; {@code s} is the mutable state, the multiplier {@code m}
+ * is fixed (the same for all instances of {@code L32X64MixRandom}}) and the addend
+ * {@code a} is a parameter (a final field of the instance). The parameter
+ * {@code a} is required to be odd (this allows the LCG to have the maximal
+ * period, namely 232); therefore there are 231 distinct choices
+ * of parameter.
+ *
+ * The Xorshift subgenerator for {@code L32X64MixRandom} is the {@code xoroshiro64} algorithm,
+ * version 1.0 (parameters 26, 9, 13), without any final scrambler such as "+" or "**".
+ * Its state consists of two {@code int} fields {@code x0} and {@code x1},
+ * which can take on any values provided that they are not both zero.
+ * The period of this subgenerator is 264-1.
+ *
+ * The mixing function for {@code L32X64MixRandom} is the "starstar" mixing function.
+ *
+ * Because the periods 232 and 264-1 of the two subgenerators
+ * are relatively prime, the period of any single {@code L32X64MixRandom} object
+ * (the length of the series of generated 32-bit values before it repeats) is the product
+ * of the periods of the subgenerators, that is, 232(264-1),
+ * which is just slightly smaller than 296. Moreover, if two distinct
+ * {@code L32X64MixRandom} objects have different {@code a} parameters, then their
+ * cycles of produced values will be different.
+ *
+ * The 32-bit values produced by the {@code nextInt()} method are exactly equidistributed.
+ * For any specific instance of {@code L32X64MixRandom}, over the course of its cycle each
+ * of the 232 possible {@code int} values will be produced 264-1 times.
+ * The values produced by the {@code nextFloat()} method are likewise exactly equidistributed.
+ *
+ * In fact, the 32-bit values produced by the {@code nextInt()} method are 2-equidistributed.
+ * To be precise: for any specific instance of {@code L32X64MixRandom}, consider
+ * the (overlapping) length-2 subsequences of the cycle of 64-bit values produced by
+ * {@code nextInt()} (assuming no other methods are called that would affect the state).
+ * There are 232(264-1) such subsequences, and each subsequence,
+ * which consists of 2 32-bit values, can have one of 264 values. Of those
+ * 264 subsequence values, nearly all of them (264-232)
+ * occur 232 times over the course of the entire cycle, and the other
+ * 232 subsequence values occur only 232-1 times. So the ratio
+ * of the probability of getting one of the less common subsequence values and the
+ * probability of getting one of the more common subsequence values is 1-2-32.
+ * (Note that the set of 232 less-common subsequence values will differ from
+ * one instance of {@code L32X64MixRandom} to another, as a function of the additive
+ * parameter of the LCG.) As a consequence, the values produced by the {@code nextFloat()}
+ * method are likewise 2-equidistributed, and the values produced by the {@code nextLong()}
+ * and {@code nextDouble()} methods are equidistributed (but not 2-equidistributed).
+ *
+ * Method {@link #split} constructs and returns a new {@code L32X64MixRandom}
+ * instance that shares no mutable state with the current instance. However, with
+ * very high probability, the values collectively generated by the two objects
+ * have the same statistical properties as if the same quantity of values were
+ * generated by a single thread using a single {@code L32X64MixRandom} object.
+ * This is because, with high probability, distinct {@code L32X64MixRandom} objects
+ * have distinct {@code a} parameters and therefore use distinct members of the
+ * algorithmic family; and even if their {@code a} parameters are the same, with
+ * very high probability they will traverse different parts of their common state
+ * cycle.
+ *
+ * As with {@link java.util.SplittableRandom}, instances of
+ * {@code L32X64MixRandom} are not thread-safe.
+ * They are designed to be split, not shared, across threads. For
+ * example, a {@link java.util.concurrent.ForkJoinTask} fork/join-style
+ * computation using random numbers might include a construction
+ * of the form {@code new Subtask(someL32X64MixRandom.split()).fork()}.
+ *
+ * This class provides additional methods for generating random
+ * streams, that employ the above techniques when used in
+ * {@code stream.parallel()} mode.
+ *
+ * Instances of {@code L32X64MixRandom} are not cryptographically
+ * secure. Consider instead using {@link java.security.SecureRandom}
+ * in security-sensitive applications. Additionally,
+ * default-constructed instances do not use a cryptographically random
+ * seed unless the {@linkplain System#getProperty system property}
+ * {@code java.util.secureRandomSeed} is set to {@code true}.
+ *
+ * @author Guy Steele
+ * @since 1.9
+ */
+public final class L32X64MixRandom extends AbstractSplittableRng {
+
+ /*
+ * Implementation Overview.
+ *
+ * The split operation uses the current generator to choose four new 64-bit
+ * int values that are then used to initialize the parameter `a` and the
+ * state variables `s`, `x0`, and `x1` for a newly constructed generator.
+ *
+ * With high probability, no two generators so chosen
+ * will have the same `a` parameter, and testing has indicated
+ * that the values generated by two instances of {@code L32X64MixRandom}
+ * will be (approximately) independent if have different values for `a`.
+ *
+ * The default (no-argument) constructor, in essence, uses
+ * "defaultGen" to generate four new 32-bit values for the same
+ * purpose. Multiple generators created in this way will certainly
+ * differ in their `a` parameters. The defaultGen state must be accessed
+ * in a thread-safe manner, so we use an AtomicLong to represent
+ * this state. To bootstrap the defaultGen, we start off using a
+ * seed based on current time unless the
+ * java.util.secureRandomSeed property is set. This serves as a
+ * slimmed-down (and insecure) variant of SecureRandom that also
+ * avoids stalls that may occur when using /dev/random.
+ *
+ * File organization: First static fields, then instance
+ * fields, then constructors, then instance methods.
+ */
+
+ /* ---------------- static fields ---------------- */
+
+ /**
+ * The seed generator for default constructors.
+ */
+ private static final AtomicLong defaultGen = new AtomicLong(RngSupport.initialSeed());
+
+ /*
+ * The period of this generator, which is (2**64 - 1) * 2**32.
+ */
+ private static final BigInteger thePeriod =
+ BigInteger.ONE.shiftLeft(64).subtract(BigInteger.ONE).shiftLeft(32);
+
+ /*
+ * Multiplier used in the LCG portion of the algorithm, taken from
+ * Pierre L'Ecuyer, Tables of linear congruential generators of
+ * different sizes and good lattice structure, Mathematics of
+ * Computation 68, 225 (January 1999), pages 249–260,
+ * Table 4 (third multiplier for size 232).
+ */
+
+ private static final int m = 32310901;
+
+ /* ---------------- instance fields ---------------- */
+
+ /**
+ * The parameter that is used as an additive constant for the LCG.
+ * Must be odd.
+ */
+ private final int a;
+
+ /**
+ * The per-instance state: s for the LCG; x0 and x1 for the xorshift.
+ * At least one of x0 and x1 must be nonzero.
+ */
+ private int s, x0, x1;
+
+ /* ---------------- constructors ---------------- */
+
+ /**
+ * Basic constructor that initializes all fields from parameters.
+ * It then adjusts the field values if necessary to ensure that
+ * all constraints on the values of fields are met.
+ */
+ public L32X64MixRandom(int a, int s, int x0, int x1) {
+ // Force a to be odd.
+ this.a = a | 1;
+ this.s = s;
+ // If x0 and x1 are both zero, we must choose nonzero values.
+ if ((x0 | x1) == 0) {
+ // At least one of the two values generated here will be nonzero.
+ this.x0 = RngSupport.mixMurmur32(s += RngSupport.GOLDEN_RATIO_32);
+ this.x1 = RngSupport.mixMurmur32(s + RngSupport.GOLDEN_RATIO_32);
+ }
+ }
+
+ /**
+ * Creates a new instance of {@code L32X64MixRandom} using the
+ * specified {@code long} value as the initial seed. Instances of
+ * {@code L32X64MixRandom} created with the same seed in the same
+ * program generate identical sequences of values.
+ *
+ * @param seed the initial seed
+ */
+ public L32X64MixRandom(long seed) {
+ // Using a value with irregularly spaced 1-bits to xor the seed
+ // argument tends to improve "pedestrian" seeds such as 0 or
+ // other small integers. We may as well use SILVER_RATIO_64.
+ //
+ // The high half of the seed is hashed by mixMurmur32 to produce the `a` parameter.
+ // The low half of the seed is hashed by mixMurmur32 to produce the initial `x0`,
+ // which will then be used to produce the first generated value.
+ // Then x1 is filled in as if by a SplitMix PRNG with
+ // GOLDEN_RATIO_32 as the gamma value and Murmur32 as the mixer.
+ this(RngSupport.mixMurmur32((int)((seed ^= RngSupport.SILVER_RATIO_64) >>> 32)),
+ 1,
+ RngSupport.mixLea32((int)(seed)),
+ RngSupport.mixLea32((int)(seed) + RngSupport.GOLDEN_RATIO_32));
+ }
+
+ /**
+ * Creates a new instance of {@code L32X64MixRandom} that is likely to
+ * generate sequences of values that are statistically independent
+ * of those of any other instances in the current program execution,
+ * but may, and typically does, vary across program invocations.
+ */
+ public L32X64MixRandom() {
+ // Using GOLDEN_RATIO_64 here gives us a good Weyl sequence of values.
+ this(defaultGen.getAndAdd(RngSupport.GOLDEN_RATIO_64));
+ }
+
+ /**
+ * Creates a new instance of {@code L32X64MixRandom} using the specified array of
+ * initial seed bytes. Instances of {@code L32X64MixRandom} created with the same
+ * seed array in the same program execution generate identical sequences of values.
+ *
+ * @param seed the initial seed
+ */
+ public L32X64MixRandom(byte[] seed) {
+ // Convert the seed to 4 int values, of which the last 2 are not all zero.
+ int[] data = RngSupport.convertSeedBytesToInts(seed, 4, 2);
+ int a = data[0], s = data[1], x0 = data[2], x1 = data[3];
+ // Force a to be odd.
+ this.a = a | 1;
+ this.s = s;
+ this.x0 = x0;
+ this.x1 = x1;
+ }
+
+ /* ---------------- public methods ---------------- */
+
+ /**
+ * Constructs and returns a new instance of {@code L32X64MixRandom}
+ * that shares no mutable state with this instance.
+ * However, with very high probability, the set of values collectively
+ * generated by the two objects has the same statistical properties as if
+ * same the quantity of values were generated by a single thread using
+ * a single {@code L32X64MixRandom} object. Either or both of the two
+ * objects may be further split using the {@code split} method,
+ * and the same expected statistical properties apply to the
+ * entire set of generators constructed by such recursive splitting.
+ *
+ * @param source a {@code SplittableRng} instance to be used instead
+ * of this one as a source of pseudorandom bits used to
+ * initialize the state of the new ones.
+ * @return a new instance of {@code L32X64MixRandom}
+ */
+ public L32X64MixRandom split(SplittableRng source) {
+ // Literally pick a new instance "at random".
+ return new L32X64MixRandom(source.nextInt(), source.nextInt(),
+ source.nextInt(), source.nextInt());
+ }
+
+ /**
+ * Returns a pseudorandom {@code int} value.
+ *
+ * @return a pseudorandom {@code int} value
+ */
+ public int nextInt() {
+ final int z = s + x0;
+ s = m * s + a; // LCG
+ int q0 = x0, q1 = x1;
+ { q1 ^= q0; q0 = Integer.rotateLeft(q0, 26); q0 = q0 ^ q1 ^ (q1 << 9); q1 = Integer.rotateLeft(q1, 13); } // xoroshiro64
+ x0 = q0; x1 = q1;
+ return Integer.rotateLeft(z * 5, 7) * 9; // "starstar" mixing function
+ }
+
+ /**
+ * Returns a pseudorandom {@code long} value.
+ *
+ * @return a pseudorandom {@code long} value
+ */
+
+ public long nextLong() {
+ return ((long)(nextInt()) << 32) | nextInt();
+ }
+
+ public BigInteger period() { return thePeriod; }
+}
diff -r c646b256fbcc -r 6d87e9f7a1ec newrandom/L64X1024MixRandom.java
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/newrandom/L64X1024MixRandom.java Thu May 23 16:45:56 2019 -0400
@@ -0,0 +1,378 @@
+/*
+ * Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
+ * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ */
+
+// package java.util;
+
+import java.math.BigInteger;
+import java.util.concurrent.atomic.AtomicLong;
+
+/**
+ * A generator of uniform pseudorandom values applicable for use in
+ * (among other contexts) isolated parallel computations that may
+ * generate subtasks. Class {@code L64X1024MixRandom} implements
+ * interfaces {@link java.util.Rng} and {@link java.util.SplittableRng},
+ * and therefore supports methods for producing pseudorandomly chosen
+ * numbers of type {@code int}, {@code long}, {@code float}, and {@code double}
+ * as well as creating new split-off {@code L64X1024MixRandom} objects,
+ * with similar usages as for class {@link java.util.SplittableRandom}.
+ *
+ * Series of generated values pass the TestU01 BigCrush and PractRand test suites
+ * that measure independence and uniformity properties of random number generators.
+ * (Most recently validated with
+ * version 1.2.3 of TestU01
+ * and version 0.90 of PractRand.
+ * Note that TestU01 BigCrush was used to test not only values produced by the {@code nextLong()}
+ * method but also the result of bit-reversing each value produced by {@code nextLong()}.)
+ * These tests validate only the methods for certain
+ * types and ranges, but similar properties are expected to hold, at
+ * least approximately, for others as well.
+ *
+ * {@code L64X1024MixRandom} is a specific member of the LXM family of algorithms
+ * for pseudorandom number generators. Every LXM generator consists of two
+ * subgenerators; one is an LCG (Linear Congruential Generator) and the other is
+ * an Xorshift generator. Each output of an LXM generator is the sum of one
+ * output from each subgenerator, possibly processed by a final mixing function
+ * (and {@code L64X1024MixRandom} does use a mixing function).
+ *
+ * The LCG subgenerator for {@code L64X1024MixRandom} has an update step of the
+ * form {@code s = m * s + a}, where {@code s}, {@code m}, and {@code a} are all
+ * of type {@code long}; {@code s} is the mutable state, the multiplier {@code m}
+ * is fixed (the same for all instances of {@code L64X1024MixRandom}}) and the addend
+ * {@code a} is a parameter (a final field of the instance). The parameter
+ * {@code a} is required to be odd (this allows the LCG to have the maximal
+ * period, namely 264); therefore there are 263 distinct choices
+ * of parameter.
+ *
+ * The Xorshift subgenerator for {@code L64X1024MixRandom} is the {@code xoroshiro1024}
+ * algorithm (parameters 25, 27, and 36), without any final scrambler such as "+" or "**".
+ * Its state consists of an array {@code x} of sixteen {@code long} values,
+ * which can take on any values provided that they are not all zero.
+ * The period of this subgenerator is 21024-1.
+ *
+ * The mixing function for {@code L64X256MixRandom} is the 64-bit MurmurHash3 finalizer.
+ *
+ * Because the periods 264 and 21024-1 of the two subgenerators
+ * are relatively prime, the period of any single {@code L64X1024MixRandom} object
+ * (the length of the series of generated 64-bit values before it repeats) is the product
+ * of the periods of the subgenerators, that is, 264(21024-1),
+ * which is just slightly smaller than 21088. Moreover, if two distinct
+ * {@code L64X1024MixRandom} objects have different {@code a} parameters, then their
+ * cycles of produced values will be different.
+ *
+ * The 64-bit values produced by the {@code nextLong()} method are exactly equidistributed.
+ * For any specific instance of {@code L64X1024MixRandom}, over the course of its cycle each
+ * of the 264 possible {@code long} values will be produced 21024-1 times.
+ * The values produced by the {@code nextInt()}, {@code nextFloat()}, and {@code nextDouble()}
+ * methods are likewise exactly equidistributed.
+ *
+ * In fact, the 64-bit values produced by the {@code nextLong()} method are 16-equidistributed.
+ * To be precise: for any specific instance of {@code L64X1024MixRandom}, consider
+ * the (overlapping) length-16 subsequences of the cycle of 64-bit values produced by
+ * {@code nextLong()} (assuming no other methods are called that would affect the state).
+ * There are 264(21024-1) such subsequences, and each subsequence,
+ * which consists of 16 64-bit values, can have one of 21024 values. Of those
+ * 21024 subsequence values, nearly all of them (21024-264)
+ * occur 264 times over the course of the entire cycle, and the other
+ * 264 subsequence values occur only 264-1 times. So the ratio
+ * of the probability of getting one of the less common subsequence values and the
+ * probability of getting one of the more common subsequence values is 1-2-64.
+ * (Note that the set of 264 less-common subsequence values will differ from
+ * one instance of {@code L64X1024MixRandom} to another, as a function of the additive
+ * parameter of the LCG.) The values produced by the {@code nextInt()}, {@code nextFloat()},
+ * and {@code nextDouble()} methods are likewise 16-equidistributed.
+ *
+ * Method {@link #split} constructs and returns a new {@code L64X1024MixRandom}
+ * instance that shares no mutable state with the current instance. However, with
+ * very high probability, the values collectively generated by the two objects
+ * have the same statistical properties as if the same quantity of values were
+ * generated by a single thread using a single {@code L64X1024MixRandom} object.
+ * This is because, with high probability, distinct {@code L64X1024MixRandom} objects
+ * have distinct {@code a} parameters and therefore use distinct members of the
+ * algorithmic family; and even if their {@code a} parameters are the same, with
+ * very high probability they will traverse different parts of their common state
+ * cycle.
+ *
+ * As with {@link java.util.SplittableRandom}, instances of
+ * {@code L64X1024MixRandom} are not thread-safe.
+ * They are designed to be split, not shared, across threads. For
+ * example, a {@link java.util.concurrent.ForkJoinTask} fork/join-style
+ * computation using random numbers might include a construction
+ * of the form {@code new Subtask(someL64X1024MixRandom.split()).fork()}.
+ *
+ * This class provides additional methods for generating random
+ * streams, that employ the above techniques when used in
+ * {@code stream.parallel()} mode.
+ *
+ * Instances of {@code L64X1024MixRandom} are not cryptographically
+ * secure. Consider instead using {@link java.security.SecureRandom}
+ * in security-sensitive applications. Additionally,
+ * default-constructed instances do not use a cryptographically random
+ * seed unless the {@linkplain System#getProperty system property}
+ * {@code java.util.secureRandomSeed} is set to {@code true}.
+ *
+ * @author Guy Steele
+ * @since 1.9
+ */
+public final class L64X1024MixRandom extends AbstractSplittableRng {
+
+ /*
+ * Implementation Overview.
+ *
+ * The split() operation uses the current generator to choose 18 new 64-bit
+ * long values that are then used to initialize the parameter `a`, the
+ * state variable `s`, and the array `x` for a newly constructed generator.
+ *
+ * With extremely high probability, no two generators so chosen
+ * will have the same `a` parameter, and testing has indicated
+ * that the values generated by two instances of {@code L64X1024MixRandom}
+ * will be (approximately) independent if have different values for `a`.
+ *
+ * The default (no-argument) constructor, in essence, uses
+ * "defaultGen" to generate 18 new 64-bit values for the same
+ * purpose. Multiple generators created in this way will certainly
+ * differ in their `a` parameters. The defaultGen state must be accessed
+ * in a thread-safe manner, so we use an AtomicLong to represent
+ * this state. To bootstrap the defaultGen, we start off using a
+ * seed based on current time unless the
+ * java.util.secureRandomSeed property is set. This serves as a
+ * slimmed-down (and insecure) variant of SecureRandom that also
+ * avoids stalls that may occur when using /dev/random.
+ *
+ * File organization: First static fields, then instance
+ * fields, then constructors, then instance methods.
+ */
+
+ /* ---------------- static fields ---------------- */
+
+ /*
+ * The length of the array x.
+ */
+
+ private static final int N = 16;
+
+ /**
+ * The seed generator for default constructors.
+ */
+ private static final AtomicLong defaultGen = new AtomicLong(RngSupport.initialSeed());
+
+ /*
+ * The period of this generator, which is (2**1024 - 1) * 2**64.
+ */
+ private static final BigInteger thePeriod =
+ BigInteger.ONE.shiftLeft(N*64).subtract(BigInteger.ONE).shiftLeft(64);
+
+ /*
+ * Multiplier used in the LCG portion of the algorithm, taken from
+ * Pierre L'Ecuyer, Tables of linear congruential generators of
+ * different sizes and good lattice structure, Mathematics of
+ * Computation 68, 225 (January 1999), pages 249–260,
+ * Table 4 (first multiplier for size 264).
+ */
+
+ private static final long m = 2862933555777941757L;
+
+ /* ---------------- instance fields ---------------- */
+
+ /**
+ * The parameter that is used as an additive constant for the LCG.
+ * Must be odd.
+ */
+ private final long a;
+
+ /**
+ * The per-instance state: s for the LCG; the array x for the xorshift;
+ * p is the rotating pointer into the array x.
+ * At least one of the 16 elements of the array x must be nonzero.
+ */
+ private long s;
+ private final long[] x;
+ private int p = N - 1;
+
+ /* ---------------- constructors ---------------- */
+
+ /**
+ * Basic constructor that initializes all fields from parameters.
+ * It then adjusts the field values if necessary to ensure that
+ * all constraints on the values of fields are met.
+ */
+ public L64X1024MixRandom(long a, long s,
+ long x0, long x1, long x2, long x3,
+ long x4, long x5, long x6, long x7,
+ long x8, long x9, long x10, long x11,
+ long x12, long x13, long x14, long x15) {
+ // Force a to be odd.
+ this.a = a | 1;
+ this.s = s;
+ this.x = new long[N];
+ this.x[0] = x0;
+ this.x[1] = x1;
+ this.x[2] = x2;
+ this.x[3] = x3;
+ this.x[4] = x4;
+ this.x[5] = x5;
+ this.x[6] = x6;
+ this.x[7] = x7;
+ this.x[8] = x8;
+ this.x[9] = x9;
+ this.x[10] = x10;
+ this.x[11] = x11;
+ this.x[12] = x12;
+ this.x[13] = x13;
+ this.x[14] = x14;
+ this.x[15] = x15;
+ // If x0, x1, ..., x15 are all zero (very unlikely), we must choose nonzero values.
+ if ((x0 | x1 | x2 | x3 | x4 | x5 | x6 | x7 | x8 | x9 | x10 | x11 | x12 | x13 | x14 | x15) == 0) {
+ // At least fifteen of the sixteen values generated here will be nonzero.
+ for (int j = 0; j < N; j++) {
+ this.x[j] = RngSupport.mixStafford13(s += RngSupport.GOLDEN_RATIO_64);
+ }
+ }
+ }
+
+ /**
+ * Creates a new instance of {@code L64X1024MixRandom} using the
+ * specified {@code long} value as the initial seed. Instances of
+ * {@code L64X1024MixRandom} created with the same seed in the same
+ * program execution generate identical sequences of values.
+ *
+ * @param seed the initial seed
+ */
+ public L64X1024MixRandom(long seed) {
+ // Using a value with irregularly spaced 1-bits to xor the seed
+ // argument tends to improve "pedestrian" seeds such as 0 or
+ // other small integers. We may as well use SILVER_RATIO_64.
+ //
+ // The seed is hashed by mixMurmur64 to produce the `a` parameter.
+ // The seed is hashed by mixStafford13 to produce the initial `x[0]`,
+ // which will then be used to produce the first generated value.
+ // The other x values are filled in as if by a SplitMix PRNG with
+ // GOLDEN_RATIO_64 as the gamma value and Stafford13 as the mixer.
+ this(RngSupport.mixMurmur64(seed ^= RngSupport.SILVER_RATIO_64),
+ 1,
+ RngSupport.mixStafford13(seed),
+ RngSupport.mixStafford13(seed += RngSupport.GOLDEN_RATIO_64),
+ RngSupport.mixStafford13(seed += RngSupport.GOLDEN_RATIO_64),
+ RngSupport.mixStafford13(seed += RngSupport.GOLDEN_RATIO_64),
+ RngSupport.mixStafford13(seed += RngSupport.GOLDEN_RATIO_64),
+ RngSupport.mixStafford13(seed += RngSupport.GOLDEN_RATIO_64),
+ RngSupport.mixStafford13(seed += RngSupport.GOLDEN_RATIO_64),
+ RngSupport.mixStafford13(seed += RngSupport.GOLDEN_RATIO_64),
+ RngSupport.mixStafford13(seed += RngSupport.GOLDEN_RATIO_64),
+ RngSupport.mixStafford13(seed += RngSupport.GOLDEN_RATIO_64),
+ RngSupport.mixStafford13(seed += RngSupport.GOLDEN_RATIO_64),
+ RngSupport.mixStafford13(seed += RngSupport.GOLDEN_RATIO_64),
+ RngSupport.mixStafford13(seed += RngSupport.GOLDEN_RATIO_64),
+ RngSupport.mixStafford13(seed += RngSupport.GOLDEN_RATIO_64),
+ RngSupport.mixStafford13(seed += RngSupport.GOLDEN_RATIO_64),
+ RngSupport.mixStafford13(seed + RngSupport.GOLDEN_RATIO_64));
+ }
+
+ /**
+ * Creates a new instance of {@code L64X1024MixRandom} that is likely to
+ * generate sequences of values that are statistically independent
+ * of those of any other instances in the current program execution,
+ * but may, and typically does, vary across program invocations.
+ */
+ public L64X1024MixRandom() {
+ // Using GOLDEN_RATIO_64 here gives us a good Weyl sequence of values.
+ this(defaultGen.getAndAdd(RngSupport.GOLDEN_RATIO_64));
+ }
+
+ /**
+ * Creates a new instance of {@code L64X1024MixRandom} using the specified array of
+ * initial seed bytes. Instances of {@code L64X1024MixRandom} created with the same
+ * seed array in the same program execution generate identical sequences of values.
+ *
+ * @param seed the initial seed
+ */
+ public L64X1024MixRandom(byte[] seed) {
+ // Convert the seed to 18 long values, of which the last 16 are not all zero.
+ long[] data = RngSupport.convertSeedBytesToLongs(seed, 18, 16);
+ long a = data[0], s = data[1];
+ // Force a to be odd.
+ this.a = a | 1;
+ this.s = s;
+ this.x = new long[N];
+ for (int j = 0; j < N; j++) {
+ this.x[j] = data[2+j];
+ }
+ }
+
+ /* ---------------- public methods ---------------- */
+
+ /**
+ * Constructs and returns a new instance of {@code L64X1024MixRandom}
+ * that shares no mutable state with this instance.
+ * However, with very high probability, the set of values collectively
+ * generated by the two objects has the same statistical properties as if
+ * same the quantity of values were generated by a single thread using
+ * a single {@code L64X1024MixRandom} object. Either or both of the two
+ * objects may be further split using the {@code split} method,
+ * and the same expected statistical properties apply to the
+ * entire set of generators constructed by such recursive splitting.
+ *
+ * @param source a {@code SplittableRng} instance to be used instead
+ * of this one as a source of pseudorandom bits used to
+ * initialize the state of the new ones.
+ * @return a new instance of {@code L64X1024MixRandom}
+ */
+ public L64X1024MixRandom split(SplittableRng source) {
+ // Literally pick a new instance "at random".
+ return new L64X1024MixRandom(source.nextLong(), source.nextLong(),
+ source.nextLong(), source.nextLong(),
+ source.nextLong(), source.nextLong(),
+ source.nextLong(), source.nextLong(),
+ source.nextLong(), source.nextLong(),
+ source.nextLong(), source.nextLong(),
+ source.nextLong(), source.nextLong(),
+ source.nextLong(), source.nextLong(),
+ source.nextLong(), source.nextLong());
+ }
+
+ /**
+ * Returns a pseudorandom {@code long} value.
+ *
+ * @return a pseudorandom {@code long} value
+ */
+
+ public long nextLong() {
+ // First part of xoroshiro1024: fetch array data
+ final int q = p;
+ final long s0 = x[p = (p + 1) & (N - 1)];
+ long s15 = x[q];
+
+ final long z = s + s0;
+ s = m * s + a; // LCG
+
+ // Second part of xoroshiro1024: update array data
+ s15 ^= s0;
+ x[q] = Long.rotateLeft(s0, 25) ^ s15 ^ (s15 << 27);
+ x[p] = Long.rotateLeft(s15, 36);
+
+ return RngSupport.mixLea64(z); // mixing function
+ }
+
+ public BigInteger period() { return thePeriod; }
+}
diff -r c646b256fbcc -r 6d87e9f7a1ec newrandom/L64X1024Random.java
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/newrandom/L64X1024Random.java Thu May 23 16:45:56 2019 -0400
@@ -0,0 +1,375 @@
+/*
+ * Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
+ * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ */
+
+// package java.util;
+
+import java.math.BigInteger;
+import java.util.concurrent.atomic.AtomicLong;
+
+/**
+ * A generator of uniform pseudorandom values applicable for use in
+ * (among other contexts) isolated parallel computations that may
+ * generate subtasks. Class {@code L64X1024Random} implements
+ * interfaces {@link java.util.Rng} and {@link java.util.SplittableRng},
+ * and therefore supports methods for producing pseudorandomly chosen
+ * numbers of type {@code int}, {@code long}, {@code float}, and {@code double}
+ * as well as creating new split-off {@code L64X1024Random} objects,
+ * with similar usages as for class {@link java.util.SplittableRandom}.
+ *
+ * Series of generated values pass the TestU01 BigCrush and PractRand test suites
+ * that measure independence and uniformity properties of random number generators.
+ * (Most recently validated with
+ * version 1.2.3 of TestU01
+ * and version 0.90 of PractRand.
+ * Note that TestU01 BigCrush was used to test not only values produced by the {@code nextLong()}
+ * method but also the result of bit-reversing each value produced by {@code nextLong()}.)
+ * These tests validate only the methods for certain
+ * types and ranges, but similar properties are expected to hold, at
+ * least approximately, for others as well.
+ *
+ * {@code L64X1024Random} is a specific member of the LXM family of algorithms
+ * for pseudorandom number generators. Every LXM generator consists of two
+ * subgenerators; one is an LCG (Linear Congruential Generator) and the other is
+ * an Xorshift generator. Each output of an LXM generator is the sum of one
+ * output from each subgenerator, possibly processed by a final mixing function
+ * (but {@code L64X1024Random} does not use a mixing function).
+ *
+ * The LCG subgenerator for {@code L64X1024Random} has an update step of the
+ * form {@code s = m * s + a}, where {@code s}, {@code m}, and {@code a} are all
+ * of type {@code long}; {@code s} is the mutable state, the multiplier {@code m}
+ * is fixed (the same for all instances of {@code L64X1024Random}}) and the addend
+ * {@code a} is a parameter (a final field of the instance). The parameter
+ * {@code a} is required to be odd (this allows the LCG to have the maximal
+ * period, namely 264); therefore there are 263 distinct choices
+ * of parameter.
+ *
+ * The Xorshift subgenerator for {@code L64X1024Random} is the {@code xoroshiro1024}
+ * algorithm (parameters 25, 27, and 36), without any final scrambler such as "+" or "**".
+ * Its state consists of an array {@code x} of sixteen {@code long} values,
+ * which can take on any values provided that they are not all zero.
+ * The period of this subgenerator is 21024-1.
+ *
+ * Because the periods 264 and 21024-1 of the two subgenerators
+ * are relatively prime, the period of any single {@code L64X1024Random} object
+ * (the length of the series of generated 64-bit values before it repeats) is the product
+ * of the periods of the subgenerators, that is, 264(21024-1),
+ * which is just slightly smaller than 21088. Moreover, if two distinct
+ * {@code L64X1024Random} objects have different {@code a} parameters, then their
+ * cycles of produced values will be different.
+ *
+ * The 64-bit values produced by the {@code nextLong()} method are exactly equidistributed.
+ * For any specific instance of {@code L64X1024Random}, over the course of its cycle each
+ * of the 264 possible {@code long} values will be produced 21024-1 times.
+ * The values produced by the {@code nextInt()}, {@code nextFloat()}, and {@code nextDouble()}
+ * methods are likewise exactly equidistributed.
+ *
+ * In fact, the 64-bit values produced by the {@code nextLong()} method are 16-equidistributed.
+ * To be precise: for any specific instance of {@code L64X1024Random}, consider
+ * the (overlapping) length-16 subsequences of the cycle of 64-bit values produced by
+ * {@code nextLong()} (assuming no other methods are called that would affect the state).
+ * There are 264(21024-1) such subsequences, and each subsequence,
+ * which consists of 16 64-bit values, can have one of 21024 values. Of those
+ * 21024 subsequence values, nearly all of them (21024-264)
+ * occur 264 times over the course of the entire cycle, and the other
+ * 264 subsequence values occur only 264-1 times. So the ratio
+ * of the probability of getting one of the less common subsequence values and the
+ * probability of getting one of the more common subsequence values is 1-2-64.
+ * (Note that the set of 264 less-common subsequence values will differ from
+ * one instance of {@code L64X1024Random} to another, as a function of the additive
+ * parameter of the LCG.) The values produced by the {@code nextInt()}, {@code nextFloat()},
+ * and {@code nextDouble()} methods are likewise 16-equidistributed.
+ *
+ * Method {@link #split} constructs and returns a new {@code L64X1024Random}
+ * instance that shares no mutable state with the current instance. However, with
+ * very high probability, the values collectively generated by the two objects
+ * have the same statistical properties as if the same quantity of values were
+ * generated by a single thread using a single {@code L64X1024Random} object.
+ * This is because, with high probability, distinct {@code L64X1024Random} objects
+ * have distinct {@code a} parameters and therefore use distinct members of the
+ * algorithmic family; and even if their {@code a} parameters are the same, with
+ * very high probability they will traverse different parts of their common state
+ * cycle.
+ *
+ * As with {@link java.util.SplittableRandom}, instances of
+ * {@code L64X1024Random} are not thread-safe.
+ * They are designed to be split, not shared, across threads. For
+ * example, a {@link java.util.concurrent.ForkJoinTask} fork/join-style
+ * computation using random numbers might include a construction
+ * of the form {@code new Subtask(someL64X1024Random.split()).fork()}.
+ *
+ * This class provides additional methods for generating random
+ * streams, that employ the above techniques when used in
+ * {@code stream.parallel()} mode.
+ *
+ * Instances of {@code L64X1024Random} are not cryptographically
+ * secure. Consider instead using {@link java.security.SecureRandom}
+ * in security-sensitive applications. Additionally,
+ * default-constructed instances do not use a cryptographically random
+ * seed unless the {@linkplain System#getProperty system property}
+ * {@code java.util.secureRandomSeed} is set to {@code true}.
+ *
+ * @author Guy Steele
+ * @since 1.9
+ */
+public final class L64X1024Random extends AbstractSplittableRng {
+
+ /*
+ * Implementation Overview.
+ *
+ * The split() operation uses the current generator to choose 18 new 64-bit
+ * long values that are then used to initialize the parameter `a`, the
+ * state variable `s`, and the array `x` for a newly constructed generator.
+ *
+ * With extremely high probability, no two generators so chosen
+ * will have the same `a` parameter, and testing has indicated
+ * that the values generated by two instances of {@code L64X1024Random}
+ * will be (approximately) independent if have different values for `a`.
+ *
+ * The default (no-argument) constructor, in essence, uses
+ * "defaultGen" to generate 18 new 64-bit values for the same
+ * purpose. Multiple generators created in this way will certainly
+ * differ in their `a` parameters. The defaultGen state must be accessed
+ * in a thread-safe manner, so we use an AtomicLong to represent
+ * this state. To bootstrap the defaultGen, we start off using a
+ * seed based on current time unless the
+ * java.util.secureRandomSeed property is set. This serves as a
+ * slimmed-down (and insecure) variant of SecureRandom that also
+ * avoids stalls that may occur when using /dev/random.
+ *
+ * File organization: First static fields, then instance
+ * fields, then constructors, then instance methods.
+ */
+
+ /* ---------------- static fields ---------------- */
+
+ /*
+ * The length of the array x.
+ */
+
+ private static final int N = 16;
+
+ /**
+ * The seed generator for default constructors.
+ */
+ private static final AtomicLong defaultGen = new AtomicLong(RngSupport.initialSeed());
+
+ /*
+ * The period of this generator, which is (2**1024 - 1) * 2**64.
+ */
+ private static final BigInteger thePeriod =
+ BigInteger.ONE.shiftLeft(N*64).subtract(BigInteger.ONE).shiftLeft(64);
+
+ /*
+ * Multiplier used in the LCG portion of the algorithm, taken from
+ * Pierre L'Ecuyer, Tables of linear congruential generators of
+ * different sizes and good lattice structure, Mathematics of
+ * Computation 68, 225 (January 1999), pages 249–260,
+ * Table 4 (first multiplier for size 264).
+ */
+
+ private static final long m = 2862933555777941757L;
+
+ /* ---------------- instance fields ---------------- */
+
+ /**
+ * The parameter that is used as an additive constant for the LCG.
+ * Must be odd.
+ */
+ private final long a;
+
+ /**
+ * The per-instance state: s for the LCG; the array x for the xorshift;
+ * p is the rotating pointer into the array x.
+ * At least one of the 16 elements of the array x must be nonzero.
+ */
+ private long s;
+ private final long[] x;
+ private int p = N - 1;
+
+ /* ---------------- constructors ---------------- */
+
+ /**
+ * Basic constructor that initializes all fields from parameters.
+ * It then adjusts the field values if necessary to ensure that
+ * all constraints on the values of fields are met.
+ */
+ public L64X1024Random(long a, long s,
+ long x0, long x1, long x2, long x3,
+ long x4, long x5, long x6, long x7,
+ long x8, long x9, long x10, long x11,
+ long x12, long x13, long x14, long x15) {
+ // Force a to be odd.
+ this.a = a | 1;
+ this.s = s;
+ this.x = new long[N];
+ this.x[0] = x0;
+ this.x[1] = x1;
+ this.x[2] = x2;
+ this.x[3] = x3;
+ this.x[4] = x4;
+ this.x[5] = x5;
+ this.x[6] = x6;
+ this.x[7] = x7;
+ this.x[8] = x8;
+ this.x[9] = x9;
+ this.x[10] = x10;
+ this.x[11] = x11;
+ this.x[12] = x12;
+ this.x[13] = x13;
+ this.x[14] = x14;
+ this.x[15] = x15;
+ // If x0, x1, ..., x15 are all zero (very unlikely), we must choose nonzero values.
+ if ((x0 | x1 | x2 | x3 | x4 | x5 | x6 | x7 | x8 | x9 | x10 | x11 | x12 | x13 | x14 | x15) == 0) {
+ for (int j = 0; j < N; j++) {
+ this.x[j] = RngSupport.mixStafford13(s += RngSupport.GOLDEN_RATIO_64);
+ }
+ }
+ }
+
+ /**
+ * Creates a new instance of {@code L64X1024Random} using the
+ * specified {@code long} value as the initial seed. Instances of
+ * {@code L64X1024Random} created with the same seed in the same
+ * program execution generate identical sequences of values.
+ *
+ * @param seed the initial seed
+ */
+ public L64X1024Random(long seed) {
+ // Using a value with irregularly spaced 1-bits to xor the seed
+ // argument tends to improve "pedestrian" seeds such as 0 or
+ // other small integers. We may as well use SILVER_RATIO_64.
+ //
+ // The seed is hashed by mixMurmur64 to produce the `a` parameter.
+ // The seed is hashed by mixStafford13 to produce the initial `x[0]`,
+ // which will then be used to produce the first generated value.
+ // The other x values are filled in as if by a SplitMix PRNG with
+ // GOLDEN_RATIO_64 as the gamma value and Stafford13 as the mixer.
+ this(RngSupport.mixMurmur64(seed ^= RngSupport.SILVER_RATIO_64),
+ 1,
+ RngSupport.mixStafford13(seed),
+ RngSupport.mixStafford13(seed += RngSupport.GOLDEN_RATIO_64),
+ RngSupport.mixStafford13(seed += RngSupport.GOLDEN_RATIO_64),
+ RngSupport.mixStafford13(seed += RngSupport.GOLDEN_RATIO_64),
+ RngSupport.mixStafford13(seed += RngSupport.GOLDEN_RATIO_64),
+ RngSupport.mixStafford13(seed += RngSupport.GOLDEN_RATIO_64),
+ RngSupport.mixStafford13(seed += RngSupport.GOLDEN_RATIO_64),
+ RngSupport.mixStafford13(seed += RngSupport.GOLDEN_RATIO_64),
+ RngSupport.mixStafford13(seed += RngSupport.GOLDEN_RATIO_64),
+ RngSupport.mixStafford13(seed += RngSupport.GOLDEN_RATIO_64),
+ RngSupport.mixStafford13(seed += RngSupport.GOLDEN_RATIO_64),
+ RngSupport.mixStafford13(seed += RngSupport.GOLDEN_RATIO_64),
+ RngSupport.mixStafford13(seed += RngSupport.GOLDEN_RATIO_64),
+ RngSupport.mixStafford13(seed += RngSupport.GOLDEN_RATIO_64),
+ RngSupport.mixStafford13(seed += RngSupport.GOLDEN_RATIO_64),
+ RngSupport.mixStafford13(seed + RngSupport.GOLDEN_RATIO_64));
+ }
+
+ /**
+ * Creates a new instance of {@code L64X1024Random} that is likely to
+ * generate sequences of values that are statistically independent
+ * of those of any other instances in the current program execution,
+ * but may, and typically does, vary across program invocations.
+ */
+ public L64X1024Random() {
+ // Using GOLDEN_RATIO_64 here gives us a good Weyl sequence of values.
+ this(defaultGen.getAndAdd(RngSupport.GOLDEN_RATIO_64));
+ }
+
+ /**
+ * Creates a new instance of {@code L64X1024Random} using the specified array of
+ * initial seed bytes. Instances of {@code L64X1024Random} created with the same
+ * seed array in the same program execution generate identical sequences of values.
+ *
+ * @param seed the initial seed
+ */
+ public L64X1024Random(byte[] seed) {
+ // Convert the seed to 18 long values, of which the last 16 are not all zero.
+ long[] data = RngSupport.convertSeedBytesToLongs(seed, 18, 16);
+ long a = data[0], s = data[1];
+ // Force a to be odd.
+ this.a = a | 1;
+ this.s = s;
+ this.x = new long[N];
+ for (int j = 0; j < N; j++) {
+ this.x[j] = data[2+j];
+ }
+ }
+
+ /* ---------------- public methods ---------------- */
+
+ /**
+ * Constructs and returns a new instance of {@code L64X1024Random}
+ * that shares no mutable state with this instance.
+ * However, with very high probability, the set of values collectively
+ * generated by the two objects has the same statistical properties as if
+ * same the quantity of values were generated by a single thread using
+ * a single {@code L64X1024Random} object. Either or both of the two
+ * objects may be further split using the {@code split} method,
+ * and the same expected statistical properties apply to the
+ * entire set of generators constructed by such recursive splitting.
+ *
+ * @param source a {@code SplittableRng} instance to be used instead
+ * of this one as a source of pseudorandom bits used to
+ * initialize the state of the new ones.
+ * @return a new instance of {@code L64X1024Random}
+ */
+ public L64X1024Random split(SplittableRng source) {
+ // Literally pick a new instance "at random".
+ return new L64X1024Random(source.nextLong(), source.nextLong(),
+ source.nextLong(), source.nextLong(),
+ source.nextLong(), source.nextLong(),
+ source.nextLong(), source.nextLong(),
+ source.nextLong(), source.nextLong(),
+ source.nextLong(), source.nextLong(),
+ source.nextLong(), source.nextLong(),
+ source.nextLong(), source.nextLong(),
+ source.nextLong(), source.nextLong());
+ }
+
+ /**
+ * Returns a pseudorandom {@code long} value.
+ *
+ * @return a pseudorandom {@code long} value
+ */
+
+ public long nextLong() {
+ // First part of xoroshiro1024: fetch array data
+ final int q = p;
+ final long s0 = x[p = (p + 1) & (N - 1)];
+ long s15 = x[q];
+
+ final long z = s + s0;
+ s = m * s + a; // LCG
+
+ // Second part of xoroshiro1024: update array data
+ s15 ^= s0;
+ x[q] = Long.rotateLeft(s0, 25) ^ s15 ^ (s15 << 27);
+ x[p] = Long.rotateLeft(s15, 36);
+
+ return z;
+ }
+
+ public BigInteger period() { return thePeriod; }
+}
diff -r c646b256fbcc -r 6d87e9f7a1ec newrandom/L64X128MixRandom.java
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/newrandom/L64X128MixRandom.java Thu May 23 16:45:56 2019 -0400
@@ -0,0 +1,318 @@
+/*
+ * Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
+ * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ */
+
+// package java.util;
+
+import java.math.BigInteger;
+import java.util.concurrent.atomic.AtomicLong;
+
+/**
+ * A generator of uniform pseudorandom values applicable for use in
+ * (among other contexts) isolated parallel computations that may
+ * generate subtasks. Class {@code L64X128MixRandom} implements
+ * interfaces {@link java.util.Rng} and {@link java.util.SplittableRng},
+ * and therefore supports methods for producing pseudorandomly chosen
+ * numbers of type {@code int}, {@code long}, {@code float}, and {@code double}
+ * as well as creating new split-off {@code L64X128MixRandom} objects,
+ * with similar usages as for class {@link java.util.SplittableRandom}.
+ *
+ * Series of generated values pass the TestU01 BigCrush and PractRand test suites
+ * that measure independence and uniformity properties of random number generators.
+ * (Most recently validated with
+ * version 1.2.3 of TestU01
+ * and version 0.90 of PractRand.
+ * Note that TestU01 BigCrush was used to test not only values produced by the {@code nextLong()}
+ * method but also the result of bit-reversing each value produced by {@code nextLong()}.)
+ * These tests validate only the methods for certain
+ * types and ranges, but similar properties are expected to hold, at
+ * least approximately, for others as well.
+ *
+ * {@code L64X128MixRandom} is a specific member of the LXM family of algorithms
+ * for pseudorandom number generators. Every LXM generator consists of two
+ * subgenerators; one is an LCG (Linear Congruential Generator) and the other is
+ * an Xorshift generator. Each output of an LXM generator is the sum of one
+ * output from each subgenerator, possibly processed by a final mixing function
+ * (and {@code L64X128MixRandom} does use a mixing function).
+ *
+ * The LCG subgenerator for {@code L64X128MixRandom} has an update step of the
+ * form {@code s = m * s + a}, where {@code s}, {@code m}, and {@code a} are all
+ * of type {@code long}; {@code s} is the mutable state, the multiplier {@code m}
+ * is fixed (the same for all instances of {@code L64X128MixRandom}}) and the addend
+ * {@code a} is a parameter (a final field of the instance). The parameter
+ * {@code a} is required to be odd (this allows the LCG to have the maximal
+ * period, namely 264); therefore there are 263 distinct choices
+ * of parameter.
+ *
+ * The Xorshift subgenerator for {@code L64X128MixRandom} is the {@code xoroshiro128} algorithm,
+ * version 1.0 (parameters 24, 16, 37), without any final scrambler such as "+" or "**".
+ * Its state consists of two {@code long} fields {@code x0} and {@code x1},
+ * which can take on any values provided that they are not both zero.
+ * The period of this subgenerator is 2128-1.
+ *
+ * The mixing function for {@code L64X128MixRandom} is the 64-bit "starstar(5,7,9)" function.
+ *
+ * Because the periods 264 and 2128-1 of the two subgenerators
+ * are relatively prime, the period of any single {@code L64X128MixRandom} object
+ * (the length of the series of generated 64-bit values before it repeats) is the product
+ * of the periods of the subgenerators, that is, 264(2128-1),
+ * which is just slightly smaller than 2192. Moreover, if two distinct
+ * {@code L64X128MixRandom} objects have different {@code a} parameters, then their
+ * cycles of produced values will be different.
+ *
+ * The 64-bit values produced by the {@code nextLong()} method are exactly equidistributed.
+ * For any specific instance of {@code L64X128MixRandom}, over the course of its cycle each
+ * of the 264 possible {@code long} values will be produced 2128-1 times.
+ * The values produced by the {@code nextInt()}, {@code nextFloat()}, and {@code nextDouble()}
+ * methods are likewise exactly equidistributed.
+ *
+ * In fact, the 64-bit values produced by the {@code nextLong()} method are 2-equidistributed.
+ * To be precise: for any specific instance of {@code L64X128MixRandom}, consider
+ * the (overlapping) length-2 subsequences of the cycle of 64-bit values produced by
+ * {@code nextLong()} (assuming no other methods are called that would affect the state).
+ * There are 264(2128-1) such subsequences, and each subsequence,
+ * which consists of 2 64-bit values, can have one of 2128 values. Of those
+ * 2128 subsequence values, nearly all of them (2128-264)
+ * occur 264 times over the course of the entire cycle, and the other
+ * 264 subsequence values occur only 264-1 times. So the ratio
+ * of the probability of getting one of the less common subsequence values and the
+ * probability of getting one of the more common subsequence values is 1-2-64.
+ * (Note that the set of 264 less-common subsequence values will differ from
+ * one instance of {@code L64X128MixRandom} to another, as a function of the additive
+ * parameter of the LCG.) The values produced by the {@code nextInt()}, {@code nextFloat()},
+ * and {@code nextDouble()} methods are likewise 2-equidistributed.
+ *
+ * Method {@link #split} constructs and returns a new {@code L64X128MixRandom}
+ * instance that shares no mutable state with the current instance. However, with
+ * very high probability, the values collectively generated by the two objects
+ * have the same statistical properties as if the same quantity of values were
+ * generated by a single thread using a single {@code L64X128MixRandom} object.
+ * This is because, with high probability, distinct {@code L64X128MixRandom} objects
+ * have distinct {@code a} parameters and therefore use distinct members of the
+ * algorithmic family; and even if their {@code a} parameters are the same, with
+ * very high probability they will traverse different parts of their common state
+ * cycle.
+ *
+ * As with {@link java.util.SplittableRandom}, instances of
+ * {@code L64X128MixRandom} are not thread-safe.
+ * They are designed to be split, not shared, across threads. For
+ * example, a {@link java.util.concurrent.ForkJoinTask} fork/join-style
+ * computation using random numbers might include a construction
+ * of the form {@code new Subtask(someL64X128MixRandom.split()).fork()}.
+ *
+ * This class provides additional methods for generating random
+ * streams, that employ the above techniques when used in
+ * {@code stream.parallel()} mode.
+ *
+ * Instances of {@code L64X128MixRandom} are not cryptographically
+ * secure. Consider instead using {@link java.security.SecureRandom}
+ * in security-sensitive applications. Additionally,
+ * default-constructed instances do not use a cryptographically random
+ * seed unless the {@linkplain System#getProperty system property}
+ * {@code java.util.secureRandomSeed} is set to {@code true}.
+ *
+ * @author Guy Steele
+ * @since 1.9
+ */
+public final class L64X128MixRandom extends AbstractSplittableRng {
+
+ /*
+ * Implementation Overview.
+ *
+ * The split operation uses the current generator to choose four new 64-bit
+ * long values that are then used to initialize the parameter `a` and the
+ * state variables `s`, `x0`, and `x1` for a newly constructed generator.
+ *
+ * With extremely high probability, no two generators so chosen
+ * will have the same `a` parameter, and testing has indicated
+ * that the values generated by two instances of {@code L64X128MixRandom}
+ * will be (approximately) independent if have different values for `a`.
+ *
+ * The default (no-argument) constructor, in essence, uses
+ * "defaultGen" to generate four new 64-bit values for the same
+ * purpose. Multiple generators created in this way will certainly
+ * differ in their `a` parameters. The defaultGen state must be accessed
+ * in a thread-safe manner, so we use an AtomicLong to represent
+ * this state. To bootstrap the defaultGen, we start off using a
+ * seed based on current time unless the
+ * java.util.secureRandomSeed property is set. This serves as a
+ * slimmed-down (and insecure) variant of SecureRandom that also
+ * avoids stalls that may occur when using /dev/random.
+ *
+ * File organization: First static fields, then instance
+ * fields, then constructors, then instance methods.
+ */
+
+ /* ---------------- static fields ---------------- */
+
+ /**
+ * The seed generator for default constructors.
+ */
+ private static final AtomicLong defaultGen = new AtomicLong(RngSupport.initialSeed());
+
+ /*
+ * The period of this generator, which is (2**128 - 1) * 2**64.
+ */
+ private static final BigInteger thePeriod =
+ BigInteger.ONE.shiftLeft(128).subtract(BigInteger.ONE).shiftLeft(64);
+
+ /*
+ * Multiplier used in the LCG portion of the algorithm, taken from
+ * Pierre L'Ecuyer, Tables of linear congruential generators of
+ * different sizes and good lattice structure, Mathematics of
+ * Computation 68, 225 (January 1999), pages 249–260,
+ * Table 4 (first multiplier for size 264).
+ */
+
+ private static final long m = 2862933555777941757L;
+
+ /* ---------------- instance fields ---------------- */
+
+ /**
+ * The parameter that is used as an additive constant for the LCG.
+ * Must be odd.
+ */
+ private final long a;
+
+ /**
+ * The per-instance state: s for the LCG; x0 and x1 for the xorshift.
+ * At least one of x0 and x1 must be nonzero.
+ */
+ private long s, x0, x1;
+
+ /* ---------------- constructors ---------------- */
+
+ /**
+ * Basic constructor that initializes all fields from parameters.
+ * It then adjusts the field values if necessary to ensure that
+ * all constraints on the values of fields are met.
+ */
+ public L64X128MixRandom(long a, long s, long x0, long x1) {
+ // Force a to be odd.
+ this.a = a | 1;
+ this.s = s;
+ this.x0 = x0;
+ this.x1 = x1;
+ // If x0 and x1 are both zero, we must choose nonzero values.
+ if ((x0 | x1) == 0) {
+ // At least one of the two values generated here will be nonzero.
+ this.x0 = RngSupport.mixStafford13(s += RngSupport.GOLDEN_RATIO_64);
+ this.x1 = RngSupport.mixStafford13(s + RngSupport.GOLDEN_RATIO_64);
+ }
+ }
+
+ /**
+ * Creates a new instance of {@code L64X128MixRandom} using the
+ * specified {@code long} value as the initial seed. Instances of
+ * {@code L64X128MixRandom} created with the same seed in the same
+ * program generate identical sequences of values.
+ *
+ * @param seed the initial seed
+ */
+ public L64X128MixRandom(long seed) {
+ // Using a value with irregularly spaced 1-bits to xor the seed
+ // argument tends to improve "pedestrian" seeds such as 0 or
+ // other small integers. We may as well use SILVER_RATIO_64.
+ //
+ // The seed is hashed by mixMurmur64 to produce the `a` parameter.
+ // The seed is hashed by mixStafford13 to produce the initial `x0`,
+ // which will then be used to produce the first generated value.
+ // Then x1 is filled in as if by a SplitMix PRNG with
+ // GOLDEN_RATIO_64 as the gamma value and Stafford13 as the mixer.
+ this(RngSupport.mixMurmur64(seed ^= RngSupport.SILVER_RATIO_64),
+ 1,
+ RngSupport.mixStafford13(seed),
+ RngSupport.mixStafford13(seed + RngSupport.GOLDEN_RATIO_64));
+ }
+
+ /**
+ * Creates a new instance of {@code L64X128MixRandom} that is likely to
+ * generate sequences of values that are statistically independent
+ * of those of any other instances in the current program execution,
+ * but may, and typically does, vary across program invocations.
+ */
+ public L64X128MixRandom() {
+ // Using GOLDEN_RATIO_64 here gives us a good Weyl sequence of values.
+ this(defaultGen.getAndAdd(RngSupport.GOLDEN_RATIO_64));
+ }
+
+ /**
+ * Creates a new instance of {@code L64X128MixRandom} using the specified array of
+ * initial seed bytes. Instances of {@code L64X128MixRandom} created with the same
+ * seed array in the same program execution generate identical sequences of values.
+ *
+ * @param seed the initial seed
+ */
+ public L64X128MixRandom(byte[] seed) {
+ // Convert the seed to 4 long values, of which the last 2 are not all zero.
+ long[] data = RngSupport.convertSeedBytesToLongs(seed, 4, 2);
+ long a = data[0], s = data[1], x0 = data[2], x1 = data[3];
+ // Force a to be odd.
+ this.a = a | 1;
+ this.s = s;
+ this.x0 = x0;
+ this.x1 = x1;
+ }
+
+ /* ---------------- public methods ---------------- */
+
+ /**
+ * Constructs and returns a new instance of {@code L64X128MixRandom}
+ * that shares no mutable state with this instance.
+ * However, with very high probability, the set of values collectively
+ * generated by the two objects has the same statistical properties as if
+ * same the quantity of values were generated by a single thread using
+ * a single {@code L64X128MixRandom} object. Either or both of the two
+ * objects may be further split using the {@code split} method,
+ * and the same expected statistical properties apply to the
+ * entire set of generators constructed by such recursive splitting.
+ *
+ * @param source a {@code SplittableRng} instance to be used instead
+ * of this one as a source of pseudorandom bits used to
+ * initialize the state of the new ones.
+ * @return a new instance of {@code L64X128MixRandom}
+ */
+ public L64X128MixRandom split(SplittableRng source) {
+ // Literally pick a new instance "at random".
+ return new L64X128MixRandom(source.nextLong(), source.nextLong(),
+ source.nextLong(), source.nextLong());
+ }
+
+ /**
+ * Returns a pseudorandom {@code long} value.
+ *
+ * @return a pseudorandom {@code long} value
+ */
+
+ public long nextLong() {
+ final long z = s + x0;
+ s = m * s + a; // LCG
+ long q0 = x0, q1 = x1;
+ { q1 ^= q0; q0 = Long.rotateLeft(q0, 24); q0 = q0 ^ q1 ^ (q1 << 16); q1 = Long.rotateLeft(q1, 37); } // xoroshiro128v1_0
+ x0 = q0; x1 = q1;
+ return Long.rotateLeft(z * 5, 7) * 9; // "starstar" mixing function
+ }
+
+ public BigInteger period() { return thePeriod; }
+}
diff -r c646b256fbcc -r 6d87e9f7a1ec newrandom/L64X128Random.java
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/newrandom/L64X128Random.java Thu May 23 16:45:56 2019 -0400
@@ -0,0 +1,314 @@
+/*
+ * Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
+ * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ */
+
+// package java.util;
+
+import java.math.BigInteger;
+import java.util.concurrent.atomic.AtomicLong;
+
+/**
+ * A generator of uniform pseudorandom values applicable for use in
+ * (among other contexts) isolated parallel computations that may
+ * generate subtasks. Class {@code L64X128Random} implements
+ * interfaces {@link java.util.Rng} and {@link java.util.SplittableRng},
+ * and therefore supports methods for producing pseudorandomly chosen
+ * numbers of type {@code int}, {@code long}, {@code float}, and {@code double}
+ * as well as creating new split-off {@code L64X128Random} objects,
+ * with similar usages as for class {@link java.util.SplittableRandom}.
+ *
+ * Series of generated values pass the TestU01 BigCrush and PractRand test suites
+ * that measure independence and uniformity properties of random number generators.
+ * (Most recently validated with
+ * version 1.2.3 of TestU01
+ * and version 0.90 of PractRand.
+ * Note that TestU01 BigCrush was used to test not only values produced by the {@code nextLong()}
+ * method but also the result of bit-reversing each value produced by {@code nextLong()}.)
+ * These tests validate only the methods for certain
+ * types and ranges, but similar properties are expected to hold, at
+ * least approximately, for others as well.
+ *
+ * {@code L64X128Random} is a specific member of the LXM family of algorithms
+ * for pseudorandom number generators. Every LXM generator consists of two
+ * subgenerators; one is an LCG (Linear Congruential Generator) and the other is
+ * an Xorshift generator. Each output of an LXM generator is the sum of one
+ * output from each subgenerator, possibly processed by a final mixing function
+ * (but {@code L64X128Random} does not use a mixing function).
+ *
+ * The LCG subgenerator for {@code L64X128Random} has an update step of the
+ * form {@code s = m * s + a}, where {@code s}, {@code m}, and {@code a} are all
+ * of type {@code long}; {@code s} is the mutable state, the multiplier {@code m}
+ * is fixed (the same for all instances of {@code L64X128Random}}) and the addend
+ * {@code a} is a parameter (a final field of the instance). The parameter
+ * {@code a} is required to be odd (this allows the LCG to have the maximal
+ * period, namely 264); therefore there are 263 distinct choices
+ * of parameter.
+ *
+ * The Xorshift subgenerator for {@code L64X128Random} is the {@code xoroshiro128} algorithm,
+ * version 1.0 (parameters 24, 16, 37), without any final scrambler such as "+" or "**".
+ * Its state consists of two {@code long} fields {@code x0} and {@code x1},
+ * which can take on any values provided that they are not both zero.
+ * The period of this subgenerator is 2128-1.
+ *
+ * Because the periods 264 and 2128-1 of the two subgenerators
+ * are relatively prime, the period of any single {@code L64X128Random} object
+ * (the length of the series of generated 64-bit values before it repeats) is the product
+ * of the periods of the subgenerators, that is, 264(2128-1),
+ * which is just slightly smaller than 2192. Moreover, if two distinct
+ * {@code L64X128Random} objects have different {@code a} parameters, then their
+ * cycles of produced values will be different.
+ *
+ * The 64-bit values produced by the {@code nextLong()} method are exactly equidistributed.
+ * For any specific instance of {@code L64X128Random}, over the course of its cycle each
+ * of the 264 possible {@code long} values will be produced 2128-1 times.
+ * The values produced by the {@code nextInt()}, {@code nextFloat()}, and {@code nextDouble()}
+ * methods are likewise exactly equidistributed.
+ *
+ * In fact, the 64-bit values produced by the {@code nextLong()} method are 2-equidistributed.
+ * To be precise: for any specific instance of {@code L64X128Random}, consider
+ * the (overlapping) length-2 subsequences of the cycle of 64-bit values produced by
+ * {@code nextLong()} (assuming no other methods are called that would affect the state).
+ * There are 264(2128-1) such subsequences, and each subsequence,
+ * which consists of 2 64-bit values, can have one of 2128 values. Of those
+ * 2128 subsequence values, nearly all of them (2128-264)
+ * occur 264 times over the course of the entire cycle, and the other
+ * 264 subsequence values occur only 264-1 times. So the ratio
+ * of the probability of getting one of the less common subsequence values and the
+ * probability of getting one of the more common subsequence values is 1-2-64.
+ * (Note that the set of 264 less-common subsequence values will differ from
+ * one instance of {@code L64X128Random} to another, as a function of the additive
+ * parameter of the LCG.) The values produced by the {@code nextInt()}, {@code nextFloat()},
+ * and {@code nextDouble()} methods are likewise 2-equidistributed.
+ *
+ * Method {@link #split} constructs and returns a new {@code L64X128Random}
+ * instance that shares no mutable state with the current instance. However, with
+ * very high probability, the values collectively generated by the two objects
+ * have the same statistical properties as if the same quantity of values were
+ * generated by a single thread using a single {@code L64X128Random} object.
+ * This is because, with high probability, distinct {@code L64X128Random} objects
+ * have distinct {@code a} parameters and therefore use distinct members of the
+ * algorithmic family; and even if their {@code a} parameters are the same, with
+ * very high probability they will traverse different parts of their common state
+ * cycle.
+ *
+ * As with {@link java.util.SplittableRandom}, instances of
+ * {@code L64X128Random} are not thread-safe.
+ * They are designed to be split, not shared, across threads. For
+ * example, a {@link java.util.concurrent.ForkJoinTask} fork/join-style
+ * computation using random numbers might include a construction
+ * of the form {@code new Subtask(someL64X128Random.split()).fork()}.
+ *
+ * This class provides additional methods for generating random
+ * streams, that employ the above techniques when used in
+ * {@code stream.parallel()} mode.
+ *
+ * Instances of {@code L64X128Random} are not cryptographically
+ * secure. Consider instead using {@link java.security.SecureRandom}
+ * in security-sensitive applications. Additionally,
+ * default-constructed instances do not use a cryptographically random
+ * seed unless the {@linkplain System#getProperty system property}
+ * {@code java.util.secureRandomSeed} is set to {@code true}.
+ *
+ * @author Guy Steele
+ * @since 1.9
+ */
+public final class L64X128Random extends AbstractSplittableRng {
+
+ /*
+ * Implementation Overview.
+ *
+ * The split operation uses the current generator to choose four new 64-bit
+ * long values that are then used to initialize the parameter `a` and the
+ * state variables `s`, `x0`, and `x1` for a newly constructed generator.
+ *
+ * With extremely high probability, no two generators so chosen
+ * will have the same `a` parameter, and testing has indicated
+ * that the values generated by two instances of {@code L64X128Random}
+ * will be (approximately) independent if have different values for `a`.
+ *
+ * The default (no-argument) constructor, in essence, uses
+ * "defaultGen" to generate four new 64-bit values for the same
+ * purpose. Multiple generators created in this way will certainly
+ * differ in their `a` parameters. The defaultGen state must be accessed
+ * in a thread-safe manner, so we use an AtomicLong to represent
+ * this state. To bootstrap the defaultGen, we start off using a
+ * seed based on current time unless the
+ * java.util.secureRandomSeed property is set. This serves as a
+ * slimmed-down (and insecure) variant of SecureRandom that also
+ * avoids stalls that may occur when using /dev/random.
+ *
+ * File organization: First static fields, then instance
+ * fields, then constructors, then instance methods.
+ */
+
+ /* ---------------- static fields ---------------- */
+
+ /**
+ * The seed generator for default constructors.
+ */
+ private static final AtomicLong defaultGen = new AtomicLong(RngSupport.initialSeed());
+
+ /*
+ * The period of this generator, which is (2**128 - 1) * 2**64.
+ */
+ private static final BigInteger thePeriod =
+ BigInteger.ONE.shiftLeft(128).subtract(BigInteger.ONE).shiftLeft(64);
+
+ /*
+ * Multiplier used in the LCG portion of the algorithm, taken from
+ * Pierre L'Ecuyer, Tables of linear congruential generators of
+ * different sizes and good lattice structure, Mathematics of
+ * Computation 68, 225 (January 1999), pages 249–260,
+ * Table 4 (first multiplier for size 264).
+ */
+
+ private static final long m = 2862933555777941757L;
+
+ /* ---------------- instance fields ---------------- */
+
+ /**
+ * The parameter that is used as an additive constant for the LCG.
+ * Must be odd.
+ */
+ private final long a;
+
+ /**
+ * The per-instance state: s for the LCG; x0 and x1 for the xorshift.
+ * At least one of x0 and x1 must be nonzero.
+ */
+ private long s, x0, x1;
+
+ /* ---------------- constructors ---------------- */
+
+ /**
+ * Basic constructor that initializes all fields from parameters.
+ * It then adjusts the field values if necessary to ensure that
+ * all constraints on the values of fields are met.
+ */
+ public L64X128Random(long a, long s, long x0, long x1) {
+ // Force a to be odd.
+ this.a = a | 1;
+ this.s = s;
+ // If x0 and x1 are both zero, we must choose nonzero values.
+ if ((x0 | x1) == 0) {
+ // At least one of the two values generated here will be nonzero.
+ this.x0 = RngSupport.mixStafford13(s += RngSupport.GOLDEN_RATIO_64);
+ this.x1 = RngSupport.mixStafford13(s + RngSupport.GOLDEN_RATIO_64);
+ }
+ }
+
+ /**
+ * Creates a new instance of {@code L64X128Random} using the
+ * specified {@code long} value as the initial seed. Instances of
+ * {@code L64X128Random} created with the same seed in the same
+ * program generate identical sequences of values.
+ *
+ * @param seed the initial seed
+ */
+ public L64X128Random(long seed) {
+ // Using a value with irregularly spaced 1-bits to xor the seed
+ // argument tends to improve "pedestrian" seeds such as 0 or
+ // other small integers. We may as well use SILVER_RATIO_64.
+ //
+ // The seed is hashed by mixMurmur64 to produce the `a` parameter.
+ // The seed is hashed by mixStafford13 to produce the initial `x0`,
+ // which will then be used to produce the first generated value.
+ // Then x1 is filled in as if by a SplitMix PRNG with
+ // GOLDEN_RATIO_64 as the gamma value and Stafford13 as the mixer.
+ this(RngSupport.mixMurmur64(seed ^= RngSupport.SILVER_RATIO_64),
+ 1,
+ RngSupport.mixStafford13(seed),
+ RngSupport.mixStafford13(seed + RngSupport.GOLDEN_RATIO_64));
+ }
+
+ /**
+ * Creates a new instance of {@code L64X128Random} that is likely to
+ * generate sequences of values that are statistically independent
+ * of those of any other instances in the current program execution,
+ * but may, and typically does, vary across program invocations.
+ */
+ public L64X128Random() {
+ // Using GOLDEN_RATIO_64 here gives us a good Weyl sequence of values.
+ this(defaultGen.getAndAdd(RngSupport.GOLDEN_RATIO_64));
+ }
+
+ /**
+ * Creates a new instance of {@code L64X128MixRandom} using the specified array of
+ * initial seed bytes. Instances of {@code L64X128MixRandom} created with the same
+ * seed array in the same program execution generate identical sequences of values.
+ *
+ * @param seed the initial seed
+ */
+ public L64X128Random(byte[] seed) {
+ // Convert the seed to 4 long values, of which the last 2 are not all zero.
+ long[] data = RngSupport.convertSeedBytesToLongs(seed, 4, 2);
+ long a = data[0], s = data[1], x0 = data[2], x1 = data[3];
+ // Force a to be odd.
+ this.a = a | 1;
+ this.s = s;
+ this.x0 = x0;
+ this.x1 = x1;
+ }
+
+ /* ---------------- public methods ---------------- */
+
+ /**
+ * Constructs and returns a new instance of {@code L64X128Random}
+ * that shares no mutable state with this instance.
+ * However, with very high probability, the set of values collectively
+ * generated by the two objects has the same statistical properties as if
+ * same the quantity of values were generated by a single thread using
+ * a single {@code L64X128Random} object. Either or both of the two
+ * objects may be further split using the {@code split} method,
+ * and the same expected statistical properties apply to the
+ * entire set of generators constructed by such recursive splitting.
+ *
+ * @param source a {@code SplittableRng} instance to be used instead
+ * of this one as a source of pseudorandom bits used to
+ * initialize the state of the new ones.
+ * @return a new instance of {@code L64X128Random}
+ */
+ public L64X128Random split(SplittableRng source) {
+ // Literally pick a new instance "at random".
+ return new L64X128Random(source.nextLong(), source.nextLong(),
+ source.nextLong(), source.nextLong());
+ }
+
+ /**
+ * Returns a pseudorandom {@code long} value.
+ *
+ * @return a pseudorandom {@code long} value
+ */
+
+ public long nextLong() {
+ final long z = s + x0;
+ s = m * s + a; // LCG
+ long q0 = x0, q1 = x1;
+ { q1 ^= q0; q0 = Long.rotateLeft(q0, 24); q0 = q0 ^ q1 ^ (q1 << 16); q1 = Long.rotateLeft(q1, 37); } // xoroshiro128v1_0
+ x0 = q0; x1 = q1;
+ return z;
+ }
+
+ public BigInteger period() { return thePeriod; }
+}
diff -r c646b256fbcc -r 6d87e9f7a1ec newrandom/L64X256MixRandom.java
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/newrandom/L64X256MixRandom.java Thu May 23 16:45:56 2019 -0400
@@ -0,0 +1,328 @@
+/*
+ * Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
+ * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ */
+
+// package java.util;
+
+import java.math.BigInteger;
+import java.util.concurrent.atomic.AtomicLong;
+
+/**
+ * A generator of uniform pseudorandom values applicable for use in
+ * (among other contexts) isolated parallel computations that may
+ * generate subtasks. Class {@code L64X256MixRandom} implements
+ * interfaces {@link java.util.Rng} and {@link java.util.SplittableRng},
+ * and therefore supports methods for producing pseudorandomly chosen
+ * numbers of type {@code int}, {@code long}, {@code float}, and {@code double}
+ * as well as creating new split-off {@code L64X256MixRandom} objects,
+ * with similar usages as for class {@link java.util.SplittableRandom}.
+ *
+ * Series of generated values pass the TestU01 BigCrush and PractRand test suites
+ * that measure independence and uniformity properties of random number generators.
+ * (Most recently validated with
+ * version 1.2.3 of TestU01
+ * and version 0.90 of PractRand.
+ * Note that TestU01 BigCrush was used to test not only values produced by the {@code nextLong()}
+ * method but also the result of bit-reversing each value produced by {@code nextLong()}.)
+ * These tests validate only the methods for certain
+ * types and ranges, but similar properties are expected to hold, at
+ * least approximately, for others as well.
+ *
+ * {@code L64X256MixRandom} is a specific member of the LXM family of algorithms
+ * for pseudorandom number generators. Every LXM generator consists of two
+ * subgenerators; one is an LCG (Linear Congruential Generator) and the other is
+ * an Xorshift generator. Each output of an LXM generator is the sum of one
+ * output from each subgenerator, possibly processed by a final mixing function
+ * (and {@code L64X256MixRandom} does use a mixing function).
+ *
+ * The LCG subgenerator for {@code L64X256MixRandom} has an update step of the
+ * form {@code s = m * s + a}, where {@code s}, {@code m}, and {@code a} are all
+ * of type {@code long}; {@code s} is the mutable state, the multiplier {@code m}
+ * is fixed (the same for all instances of {@code L64X256MixRandom}}) and the addend
+ * {@code a} is a parameter (a final field of the instance). The parameter
+ * {@code a} is required to be odd (this allows the LCG to have the maximal
+ * period, namely 264); therefore there are 263 distinct choices
+ * of parameter.
+ *
+ * The Xorshift subgenerator for {@code L64X256MixRandom} is the {@code xoshiro256} algorithm,
+ * version 1.0 (parameters 17, 45), without any final scrambler such as "+" or "**".
+ * Its state consists of four {@code long} fields {@code x0}, {@code x1}, {@code x2},
+ * and {@code x3}, which can take on any values provided that they are not all zero.
+ * The period of this subgenerator is 2256-1.
+ *
+ * The mixing function for {@code L64X256MixRandom} is the 64-bit MurmurHash3 finalizer.
+ *
+ * Because the periods 264 and 2256-1 of the two subgenerators
+ * are relatively prime, the period of any single {@code L64X256MixRandom} object
+ * (the length of the series of generated 64-bit values before it repeats) is the product
+ * of the periods of the subgenerators, that is, 264(2256-1),
+ * which is just slightly smaller than 2320. Moreover, if two distinct
+ * {@code L64X256MixRandom} objects have different {@code a} parameters, then their
+ * cycles of produced values will be different.
+ *
+ * The 64-bit values produced by the {@code nextLong()} method are exactly equidistributed.
+ * For any specific instance of {@code L64X256MixRandom}, over the course of its cycle each
+ * of the 264 possible {@code long} values will be produced 2256-1 times.
+ * The values produced by the {@code nextInt()}, {@code nextFloat()}, and {@code nextDouble()}
+ * methods are likewise exactly equidistributed.
+ *
+ * In fact, the 64-bit values produced by the {@code nextLong()} method are 4-equidistributed.
+ * To be precise: for any specific instance of {@code L64X256MixRandom}, consider
+ * the (overlapping) length-4 subsequences of the cycle of 64-bit values produced by
+ * {@code nextLong()} (assuming no other methods are called that would affect the state).
+ * There are 264(2256-1) such subsequences, and each subsequence,
+ * which consists of 4 64-bit values, can have one of 2256 values. Of those
+ * 2256 subsequence values, nearly all of them (2256-264)
+ * occur 264 times over the course of the entire cycle, and the other
+ * 264 subsequence values occur only 264-1 times. So the ratio
+ * of the probability of getting one of the less common subsequence values and the
+ * probability of getting one of the more common subsequence values is 1-2-64.
+ * (Note that the set of 264 less-common subsequence values will differ from
+ * one instance of {@code L64X256MixRandom} to another, as a function of the additive
+ * parameter of the LCG.) The values produced by the {@code nextInt()}, {@code nextFloat()},
+ * and {@code nextDouble()} methods are likewise 4-equidistributed.
+ *
+ * Method {@link #split} constructs and returns a new {@code L64X256MixRandom}
+ * instance that shares no mutable state with the current instance. However, with
+ * very high probability, the values collectively generated by the two objects
+ * have the same statistical properties as if the same quantity of values were
+ * generated by a single thread using a single {@code L64X256MixRandom} object.
+ * This is because, with high probability, distinct {@code L64X256MixRandom} objects
+ * have distinct {@code a} parameters and therefore use distinct members of the
+ * algorithmic family; and even if their {@code a} parameters are the same, with
+ * very high probability they will traverse different parts of their common state
+ * cycle.
+ *
+ * As with {@link java.util.SplittableRandom}, instances of
+ * {@code L64X256MixRandom} are not thread-safe.
+ * They are designed to be split, not shared, across threads. For
+ * example, a {@link java.util.concurrent.ForkJoinTask} fork/join-style
+ * computation using random numbers might include a construction
+ * of the form {@code new Subtask(someL64X256MixRandom.split()).fork()}.
+ *
+ * This class provides additional methods for generating random
+ * streams, that employ the above techniques when used in
+ * {@code stream.parallel()} mode.
+ *
+ * Instances of {@code L64X256MixRandom} are not cryptographically
+ * secure. Consider instead using {@link java.security.SecureRandom}
+ * in security-sensitive applications. Additionally,
+ * default-constructed instances do not use a cryptographically random
+ * seed unless the {@linkplain System#getProperty system property}
+ * {@code java.util.secureRandomSeed} is set to {@code true}.
+ *
+ * @author Guy Steele
+ * @since 1.9
+ */
+public final class L64X256MixRandom extends AbstractSplittableRng {
+
+ /*
+ * Implementation Overview.
+ *
+ * The split operation uses the current generator to choose six new 64-bit
+ * long values that are then used to initialize the parameter `a` and the
+ * state variables `s`, `x0`, `x1`, `x2`, and `x3` for a newly constructed
+ * generator.
+ *
+ * With extremely high probability, no two generators so chosen
+ * will have the same `a` parameter, and testing has indicated
+ * that the values generated by two instances of {@code L64X256MixRandom}
+ * will be (approximately) independent if have different values for `a`.
+ *
+ * The default (no-argument) constructor, in essence, uses
+ * "defaultGen" to generate six new 64-bit values for the same
+ * purpose. Multiple generators created in this way will certainly
+ * differ in their `a` parameters. The defaultGen state must be accessed
+ * in a thread-safe manner, so we use an AtomicLong to represent
+ * this state. To bootstrap the defaultGen, we start off using a
+ * seed based on current time unless the
+ * java.util.secureRandomSeed property is set. This serves as a
+ * slimmed-down (and insecure) variant of SecureRandom that also
+ * avoids stalls that may occur when using /dev/random.
+ *
+ * File organization: First static fields, then instance
+ * fields, then constructors, then instance methods.
+ */
+
+ /* ---------------- static fields ---------------- */
+
+ /**
+ * The seed generator for default constructors.
+ */
+ private static final AtomicLong defaultGen = new AtomicLong(RngSupport.initialSeed());
+
+ /*
+ * The period of this generator, which is (2**256 - 1) * 2**64.
+ */
+ private static final BigInteger thePeriod =
+ BigInteger.ONE.shiftLeft(256).subtract(BigInteger.ONE).shiftLeft(64);
+
+ /*
+ * Multiplier used in the LCG portion of the algorithm, taken from
+ * Pierre L'Ecuyer, Tables of linear congruential generators of
+ * different sizes and good lattice structure, Mathematics of
+ * Computation 68, 225 (January 1999), pages 249–260,
+ * Table 4 (first multiplier for size 264).
+ */
+
+ private static final long m = 2862933555777941757L;
+
+ /* ---------------- instance fields ---------------- */
+
+ /**
+ * The parameter that is used as an additive constant for the LCG.
+ * Must be odd.
+ */
+ private final long a;
+
+ /**
+ * The per-instance state: s for the LCG; x0, x1, x2, and x3 for the xorshift.
+ * At least one of the four fields x0, x1, x2, and x3 must be nonzero.
+ */
+ private long s, x0, x1, x2, x3;
+
+ /* ---------------- constructors ---------------- */
+
+ /**
+ * Basic constructor that initializes all fields from parameters.
+ * It then adjusts the field values if necessary to ensure that
+ * all constraints on the values of fields are met.
+ */
+ public L64X256MixRandom(long a, long s, long x0, long x1, long x2, long x3) {
+ // Force a to be odd.
+ this.a = a | 1;
+ this.s = s;
+ this.x0 = x0;
+ this.x1 = x1;
+ this.x2 = x2;
+ this.x3 = x3;
+ // If x0, x1, x2, and x3 are all zero, we must choose nonzero values.
+ if ((x0 | x1 | x2 | x3) == 0) {
+ // At least three of the four values generated here will be nonzero.
+ this.x0 = RngSupport.mixStafford13(s += RngSupport.GOLDEN_RATIO_64);
+ this.x1 = RngSupport.mixStafford13(s += RngSupport.GOLDEN_RATIO_64);
+ this.x2 = RngSupport.mixStafford13(s += RngSupport.GOLDEN_RATIO_64);
+ this.x3 = RngSupport.mixStafford13(s + RngSupport.GOLDEN_RATIO_64);
+ }
+ }
+
+ /**
+ * Creates a new instance of {@code L64X256MixRandom} using the
+ * specified {@code long} value as the initial seed. Instances of
+ * {@code L64X256MixRandom} created with the same seed in the same
+ * program generate identical sequences of values.
+ *
+ * @param seed the initial seed
+ */
+ public L64X256MixRandom(long seed) {
+ // Using a value with irregularly spaced 1-bits to xor the seed
+ // argument tends to improve "pedestrian" seeds such as 0 or
+ // other small integers. We may as well use SILVER_RATIO_64.
+ //
+ // The seed is hashed by mixMurmur64 to produce the `a` parameter.
+ // The seed is hashed by mixStafford13 to produce the initial `x0`,
+ // which will then be used to produce the first generated value.
+ // The other x values are filled in as if by a SplitMix PRNG with
+ // GOLDEN_RATIO_64 as the gamma value and Stafford13 as the mixer.
+ this(RngSupport.mixMurmur64(seed ^= RngSupport.SILVER_RATIO_64),
+ 1,
+ RngSupport.mixStafford13(seed),
+ RngSupport.mixStafford13(seed += RngSupport.GOLDEN_RATIO_64),
+ RngSupport.mixStafford13(seed += RngSupport.GOLDEN_RATIO_64),
+ RngSupport.mixStafford13(seed + RngSupport.GOLDEN_RATIO_64));
+ }
+
+ /**
+ * Creates a new instance of {@code L64X256MixRandom} that is likely to
+ * generate sequences of values that are statistically independent
+ * of those of any other instances in the current program execution,
+ * but may, and typically does, vary across program invocations.
+ */
+ public L64X256MixRandom() {
+ // Using GOLDEN_RATIO_64 here gives us a good Weyl sequence of values.
+ this(defaultGen.getAndAdd(RngSupport.GOLDEN_RATIO_64));
+ }
+
+ /**
+ * Creates a new instance of {@code L64X256MixRandom} using the specified array of
+ * initial seed bytes. Instances of {@code L64X256MixRandom} created with the same
+ * seed array in the same program execution generate identical sequences of values.
+ *
+ * @param seed the initial seed
+ */
+ public L64X256MixRandom(byte[] seed) {
+ // Convert the seed to 6 long values, of which the last 4 are not all zero.
+ long[] data = RngSupport.convertSeedBytesToLongs(seed, 6, 4);
+ long a = data[0], s = data[1], x0 = data[2], x1 = data[3], x2 = data[4], x3 = data[5];
+ // Force a to be odd.
+ this.a = a | 1;
+ this.s = s;
+ this.x0 = x0;
+ this.x1 = x1;
+ this.x2 = x2;
+ this.x3 = x3;
+ }
+
+ /* ---------------- public methods ---------------- */
+
+ /**
+ * Constructs and returns a new instance of {@code L64X256MixRandom}
+ * that shares no mutable state with this instance.
+ * However, with very high probability, the set of values collectively
+ * generated by the two objects has the same statistical properties as if
+ * same the quantity of values were generated by a single thread using
+ * a single {@code L64X256MixRandom} object. Either or both of the two
+ * objects may be further split using the {@code split} method,
+ * and the same expected statistical properties apply to the
+ * entire set of generators constructed by such recursive splitting.
+ *
+ * @param source a {@code SplittableRng} instance to be used instead
+ * of this one as a source of pseudorandom bits used to
+ * initialize the state of the new ones.
+ * @return a new instance of {@code L64X256MixRandom}
+ */
+ public L64X256MixRandom split(SplittableRng source) {
+ // Literally pick a new instance "at random".
+ return new L64X256MixRandom(source.nextLong(), source.nextLong(),
+ source.nextLong(), source.nextLong(),
+ source.nextLong(), source.nextLong());
+ }
+
+ /**
+ * Returns a pseudorandom {@code long} value.
+ *
+ * @return a pseudorandom {@code long} value
+ */
+
+ public long nextLong() {
+ final long z = s + x0;
+ s = m * s + a; // LCG
+ long q0 = x0, q1 = x1, q2 = x2, q3 = x3;
+ { long t = q1 << 17; q2 ^= q0; q3 ^= q1; q1 ^= q2; q0 ^= q3; q2 ^= t; q3 = Long.rotateLeft(q3, 45); } // xoshiro256 1.0
+ x0 = q0; x1 = q1; x2 = q2; x3 = q3;
+ return RngSupport.mixLea64(z); // mixing function
+ }
+
+ public BigInteger period() { return thePeriod; }
+}
diff -r c646b256fbcc -r 6d87e9f7a1ec newrandom/L64X256Random.java
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/newrandom/L64X256Random.java Thu May 23 16:45:56 2019 -0400
@@ -0,0 +1,326 @@
+/*
+ * Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
+ * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ */
+
+// package java.util;
+
+import java.math.BigInteger;
+import java.util.concurrent.atomic.AtomicLong;
+
+/**
+ * A generator of uniform pseudorandom values applicable for use in
+ * (among other contexts) isolated parallel computations that may
+ * generate subtasks. Class {@code L64X256Random} implements
+ * interfaces {@link java.util.Rng} and {@link java.util.SplittableRng},
+ * and therefore supports methods for producing pseudorandomly chosen
+ * numbers of type {@code int}, {@code long}, {@code float}, and {@code double}
+ * as well as creating new split-off {@code L64X256Random} objects,
+ * with similar usages as for class {@link java.util.SplittableRandom}.
+ *
+ * Series of generated values pass the TestU01 BigCrush and PractRand test suites
+ * that measure independence and uniformity properties of random number generators.
+ * (Most recently validated with
+ * version 1.2.3 of TestU01
+ * and version 0.90 of PractRand.
+ * Note that TestU01 BigCrush was used to test not only values produced by the {@code nextLong()}
+ * method but also the result of bit-reversing each value produced by {@code nextLong()}.)
+ * These tests validate only the methods for certain
+ * types and ranges, but similar properties are expected to hold, at
+ * least approximately, for others as well.
+ *
+ * {@code L64X256Random} is a specific member of the LXM family of algorithms
+ * for pseudorandom number generators. Every LXM generator consists of two
+ * subgenerators; one is an LCG (Linear Congruential Generator) and the other is
+ * an Xorshift generator. Each output of an LXM generator is the sum of one
+ * output from each subgenerator, possibly processed by a final mixing function
+ * (but {@code L64X256Random} does not use a mixing function).
+ *
+ * The LCG subgenerator for {@code L64X256Random} has an update step of the
+ * form {@code s = m * s + a}, where {@code s}, {@code m}, and {@code a} are all
+ * of type {@code long}; {@code s} is the mutable state, the multiplier {@code m}
+ * is fixed (the same for all instances of {@code L64X256Random}}) and the addend
+ * {@code a} is a parameter (a final field of the instance). The parameter
+ * {@code a} is required to be odd (this allows the LCG to have the maximal
+ * period, namely 264); therefore there are 263 distinct choices
+ * of parameter.
+ *
+ * The Xorshift subgenerator for {@code L64X256Random} is the {@code xoshiro256} algorithm,
+ * version 1.0 (parameters 17, 45), without any final scrambler such as "+" or "**".
+ * Its state consists of four {@code long} fields {@code x0}, {@code x1}, {@code x2},
+ * and {@code x3}, which can take on any values provided that they are not all zero.
+ * The period of this subgenerator is 2256-1.
+ *
+ * Because the periods 264 and 2256-1 of the two subgenerators
+ * are relatively prime, the period of any single {@code L64X256Random} object
+ * (the length of the series of generated 64-bit values before it repeats) is the product
+ * of the periods of the subgenerators, that is, 264(2256-1),
+ * which is just slightly smaller than 2320. Moreover, if two distinct
+ * {@code L64X256Random} objects have different {@code a} parameters, then their
+ * cycles of produced values will be different.
+ *
+ * The 64-bit values produced by the {@code nextLong()} method are exactly equidistributed.
+ * For any specific instance of {@code L64X256Random}, over the course of its cycle each
+ * of the 264 possible {@code long} values will be produced 2256-1 times.
+ * The values produced by the {@code nextInt()}, {@code nextFloat()}, and {@code nextDouble()}
+ * methods are likewise exactly equidistributed.
+ *
+ * In fact, the 64-bit values produced by the {@code nextLong()} method are 4-equidistributed.
+ * To be precise: for any specific instance of {@code L64X256Random}, consider
+ * the (overlapping) length-4 subsequences of the cycle of 64-bit values produced by
+ * {@code nextLong()} (assuming no other methods are called that would affect the state).
+ * There are 264(2256-1) such subsequences, and each subsequence,
+ * which consists of 4 64-bit values, can have one of 2256 values. Of those
+ * 2256 subsequence values, nearly all of them (2256-264)
+ * occur 264 times over the course of the entire cycle, and the other
+ * 264 subsequence values occur only 264-1 times. So the ratio
+ * of the probability of getting one of the less common subsequence values and the
+ * probability of getting one of the more common subsequence values is 1-2-64.
+ * (Note that the set of 264 less-common subsequence values will differ from
+ * one instance of {@code L64X256Random} to another, as a function of the additive
+ * parameter of the LCG.) The values produced by the {@code nextInt()}, {@code nextFloat()},
+ * and {@code nextDouble()} methods are likewise 4-equidistributed.
+ *
+ * Method {@link #split} constructs and returns a new {@code L64X256Random}
+ * instance that shares no mutable state with the current instance. However, with
+ * very high probability, the values collectively generated by the two objects
+ * have the same statistical properties as if the same quantity of values were
+ * generated by a single thread using a single {@code L64X256Random} object.
+ * This is because, with high probability, distinct {@code L64X256Random} objects
+ * have distinct {@code a} parameters and therefore use distinct members of the
+ * algorithmic family; and even if their {@code a} parameters are the same, with
+ * very high probability they will traverse different parts of their common state
+ * cycle.
+ *
+ * As with {@link java.util.SplittableRandom}, instances of
+ * {@code L64X256Random} are not thread-safe.
+ * They are designed to be split, not shared, across threads. For
+ * example, a {@link java.util.concurrent.ForkJoinTask} fork/join-style
+ * computation using random numbers might include a construction
+ * of the form {@code new Subtask(someL64X256Random.split()).fork()}.
+ *
+ * This class provides additional methods for generating random
+ * streams, that employ the above techniques when used in
+ * {@code stream.parallel()} mode.
+ *
+ * Instances of {@code L64X256Random} are not cryptographically
+ * secure. Consider instead using {@link java.security.SecureRandom}
+ * in security-sensitive applications. Additionally,
+ * default-constructed instances do not use a cryptographically random
+ * seed unless the {@linkplain System#getProperty system property}
+ * {@code java.util.secureRandomSeed} is set to {@code true}.
+ *
+ * @author Guy Steele
+ * @since 1.9
+ */
+public final class L64X256Random extends AbstractSplittableRng {
+
+ /*
+ * Implementation Overview.
+ *
+ * The split() operation uses the current generator to choose six new 64-bit
+ * long values that are then used to initialize the parameter `a` and the
+ * state variables `s`, `x0`, `x1`, `x2`, and `x3` for a newly constructed
+ * generator.
+ *
+ * With extremely high probability, no two generators so chosen
+ * will have the same `a` parameter, and testing has indicated
+ * that the values generated by two instances of {@code L64X256Random}
+ * will be (approximately) independent if have different values for `a`.
+ *
+ * The default (no-argument) constructor, in essence, uses
+ * "defaultGen" to generate six new 64-bit values for the same
+ * purpose. Multiple generators created in this way will certainly
+ * differ in their `a` parameters. The defaultGen state must be accessed
+ * in a thread-safe manner, so we use an AtomicLong to represent
+ * this state. To bootstrap the defaultGen, we start off using a
+ * seed based on current time unless the
+ * java.util.secureRandomSeed property is set. This serves as a
+ * slimmed-down (and insecure) variant of SecureRandom that also
+ * avoids stalls that may occur when using /dev/random.
+ *
+ * File organization: First static fields, then instance
+ * fields, then constructors, then instance methods.
+ */
+
+ /* ---------------- static fields ---------------- */
+
+ /**
+ * The seed generator for default constructors.
+ */
+ private static final AtomicLong defaultGen = new AtomicLong(RngSupport.initialSeed());
+
+ /*
+ * The period of this generator, which is (2**256 - 1) * 2**64.
+ */
+ private static final BigInteger thePeriod =
+ BigInteger.ONE.shiftLeft(256).subtract(BigInteger.ONE).shiftLeft(64);
+
+ /*
+ * Multiplier used in the LCG portion of the algorithm, taken from
+ * Pierre L'Ecuyer, Tables of linear congruential generators of
+ * different sizes and good lattice structure, Mathematics of
+ * Computation 68, 225 (January 1999), pages 249–260,
+ * Table 4 (first multiplier for size 264).
+ */
+
+ private static final long m = 2862933555777941757L;
+
+ /* ---------------- instance fields ---------------- */
+
+ /**
+ * The parameter that is used as an additive constant for the LCG.
+ * Must be odd.
+ */
+ private final long a;
+
+ /**
+ * The per-instance state: s for the LCG; x0, x1, x2, and x3 for the xorshift.
+ * At least one of the four fields x0, x1, x2, and x3 must be nonzero.
+ */
+ private long s, x0, x1, x2, x3;
+
+ /* ---------------- constructors ---------------- */
+
+ /**
+ * Basic constructor that initializes all fields from parameters.
+ * It then adjusts the field values if necessary to ensure that
+ * all constraints on the values of fields are met.
+ */
+ public L64X256Random(long a, long s, long x0, long x1, long x2, long x3) {
+ // Force a to be odd.
+ this.a = a | 1;
+ this.s = s;
+ this.x0 = x0;
+ this.x1 = x1;
+ this.x2 = x2;
+ this.x3 = x3;
+ // If x0, x1, x2, and x3 are all zero, we must choose nonzero values.
+ if ((x0 | x1 | x2 | x3) == 0) {
+ // At least three of the four values generated here will be nonzero.
+ this.x0 = RngSupport.mixStafford13(s += RngSupport.GOLDEN_RATIO_64);
+ this.x1 = RngSupport.mixStafford13(s += RngSupport.GOLDEN_RATIO_64);
+ this.x2 = RngSupport.mixStafford13(s += RngSupport.GOLDEN_RATIO_64);
+ this.x3 = RngSupport.mixStafford13(s + RngSupport.GOLDEN_RATIO_64);
+ }
+ }
+
+ /**
+ * Creates a new instance of {@code L64X256Random} using the
+ * specified {@code long} value as the initial seed. Instances of
+ * {@code L64X256Random} created with the same seed in the same
+ * program execution generate identical sequences of values.
+ *
+ * @param seed the initial seed
+ */
+ public L64X256Random(long seed) {
+ // Using a value with irregularly spaced 1-bit to xor the seed
+ // argument tends to improve "pedestrian" seeds such as 0 or
+ // other small integers. We may as well use SILVER_RATIO_64.
+ //
+ // The seed is hashed by mixMurmur64 to produce the `a` parameter.
+ // The seed is hashed by mixStafford13 to produce the initial `x0`,
+ // which will then be used to produce the first generated value.
+ // The other x values are filled in as if by a SplitMix PRNG with
+ // GOLDEN_RATIO_64 as the gamma value and Stafford13 as the mixer.
+ this(RngSupport.mixMurmur64(seed ^= RngSupport.SILVER_RATIO_64),
+ 1,
+ RngSupport.mixStafford13(seed),
+ RngSupport.mixStafford13(seed += RngSupport.GOLDEN_RATIO_64),
+ RngSupport.mixStafford13(seed += RngSupport.GOLDEN_RATIO_64),
+ RngSupport.mixStafford13(seed + RngSupport.GOLDEN_RATIO_64));
+ }
+
+ /**
+ * Creates a new instance of {@code L64X256Random} that is likely to
+ * generate sequences of values that are statistically independent
+ * of those of any other instances in the current program execution,
+ * but may, and typically does, vary across program invocations.
+ */
+ public L64X256Random() {
+ // Using GOLDEN_RATIO_64 here gives us a good Weyl sequence of values.
+ this(defaultGen.getAndAdd(RngSupport.GOLDEN_RATIO_64));
+ }
+
+ /**
+ * Creates a new instance of {@code L64X256Random} using the specified array of
+ * initial seed bytes. Instances of {@code L64X256Random} created with the same
+ * seed array in the same program execution generate identical sequences of values.
+ *
+ * @param seed the initial seed
+ */
+ public L64X256Random(byte[] seed) {
+ // Convert the seed to 6 long values, of which the last 4 are not all zero.
+ long[] data = RngSupport.convertSeedBytesToLongs(seed, 6, 4);
+ long a = data[0], s = data[1], x0 = data[2], x1 = data[3], x2 = data[4], x3 = data[5];
+ // Force a to be odd.
+ this.a = a | 1;
+ this.s = s;
+ this.x0 = x0;
+ this.x1 = x1;
+ this.x2 = x2;
+ this.x3 = x3;
+ }
+
+ /* ---------------- public methods ---------------- */
+
+ /**
+ * Constructs and returns a new instance of {@code L64X256Random}
+ * that shares no mutable state with this instance.
+ * However, with very high probability, the set of values collectively
+ * generated by the two objects has the same statistical properties as if
+ * same the quantity of values were generated by a single thread using
+ * a single {@code L64X256Random} object. Either or both of the two
+ * objects may be further split using the {@code split} method,
+ * and the same expected statistical properties apply to the
+ * entire set of generators constructed by such recursive splitting.
+ *
+ * @param source a {@code SplittableRng} instance to be used instead
+ * of this one as a source of pseudorandom bits used to
+ * initialize the state of the new ones.
+ * @return a new instance of {@code L64X256Random}
+ */
+ public L64X256Random split(SplittableRng source) {
+ // Literally pick a new instance "at random".
+ return new L64X256Random(source.nextLong(), source.nextLong(),
+ source.nextLong(), source.nextLong(),
+ source.nextLong(), source.nextLong());
+ }
+
+ /**
+ * Returns a pseudorandom {@code long} value.
+ *
+ * @return a pseudorandom {@code long} value
+ */
+
+ public long nextLong() {
+ final long z = s + x0;
+ s = m * s + a; // LCG
+ long q0 = x0, q1 = x1, q2 = x2, q3 = x3;
+ { long t = q1 << 17; q2 ^= q0; q3 ^= q1; q1 ^= q2; q0 ^= q3; q2 ^= t; q3 = Long.rotateLeft(q3, 45); } // xoshiro256 1.0
+ x0 = q0; x1 = q1; x2 = q2; x3 = q3;
+ return z;
+ }
+
+ public BigInteger period() { return thePeriod; }
+}
diff -r c646b256fbcc -r 6d87e9f7a1ec newrandom/LeapableRng.java
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/newrandom/LeapableRng.java Thu May 23 16:45:56 2019 -0400
@@ -0,0 +1,149 @@
+/*
+ * Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
+ * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ */
+// package java.util;
+
+import java.math.BigInteger;
+import java.util.stream.Stream;
+
+/**
+ * This interface is designed to provide a common protocol for objects
+ * that generate sequences of pseudorandom numbers (or Boolean values)
+ * and furthermore can easily not only jump but also Ideally, all {@code LeapableRng} objects produced by iterative
+ * leaping and jumping from a single original {@code LeapableRng} object
+ * are statistically independent of one another and individually uniform.
+ * In practice, one must settle for some approximation to independence
+ * and uniformity. In particular, a specific implementation may
+ * assume that each generator in a stream produced by the {@code leaps}
+ * method is used to produce (by jumping) a number of objects no larger
+ * than 264. Implementors are advised to use algorithms
+ * whose period is at least 2191.
+ *
+ * Methods are provided to perform a single leap operation and also
+ * to produce a stream of generators produced from the original by
+ * iterative copying and leaping of internal state. The generators
+ * produced must implement the {@code JumpableRng} interface but need
+ * not also implement the {@code LeapableRng} interface. A typical
+ * strategy for a multithreaded application is to create a single
+ * {@code LeapableRng} object, calls its {@code leaps} method exactly
+ * once, and then parcel out generators from the resulting stream, one
+ * to each thread. Then the {@code jumps} method of each such generator
+ * be called to produce a substream of generator objects.
+ *
+ * An implementation of the {@code LeapableRng} interface must provide
+ * concrete definitions for the methods {@code nextInt()}, {@code nextLong},
+ * {@code period()}, {@code copy()}, {@code jump()}, {@code defaultJumpDistance()},
+ * {@code leap()}, and {@code defaultLeapDistance()}.
+ * Default implementations are provided for all other methods.
+ *
+ * Objects that implement {@code java.util.LeapableRng} are
+ * typically not cryptographically secure. Consider instead using
+ * {@link java.security.SecureRandom} to get a cryptographically
+ * secure pseudo-random number generator for use by
+ * security-sensitive applications.
+ *
+ * @author Guy Steele
+ * @since 1.9
+ */
+interface LeapableRng extends JumpableRng {
+ /**
+ * Returns a new generator whose internal state is an exact copy
+ * of this generator (therefore their future behavior should be
+ * identical if subjected to the same series of operations).
+ *
+ * @return a new object that is a copy of this generator
+ */
+ LeapableRng copy();
+
+ /**
+ * Alter the state of this pseudorandom number generator so as to
+ * leap forward a large, fixed distance (typically 296
+ * or more) within its state cycle.
+ */
+ void leap();
+
+ /**
+ * Returns the distance by which the {@code leap()} method will leap
+ * forward within the state cycle of this generator object.
+ *
+ * @return the default leap distance (as a {@code double} value)
+ */
+ double defaultLeapDistance();
+
+ /**
+ * Returns an effectively unlimited stream of new pseudorandom
+ * number generators, each of which implements the {@code JumpableRng}
+ * interface.
+ *
+ * @implNote It is permitted to implement this method in a manner
+ * equivalent to {@code leaps(Long.MAX_VALUE)}.
+ *
+ * @implNote The default implementation produces a sequential stream
+ * that repeatedly calls {@code copy()} and {@code leap()} on this generator,
+ * and the copies become the generators produced by the stream.
+ *
+ * @return a stream of objects that implement the {@code JumpableRng} interface
+ */
+ default Stream Instances {@code Xoroshiro128Plus} are not thread-safe.
+ * They are designed to be used so that each thread as its own instance.
+ * The methods {@link #jump} and {@link #leap} and {@link #jumps} and {@link #leaps}
+ * can be used to construct new instances of {@code Xoroshiro128Plus} that traverse
+ * other parts of the state cycle.
+ *
+ * Instances of {@code MRG32k3a} are not cryptographically
+ * secure. Consider instead using {@link java.security.SecureRandom}
+ * in security-sensitive applications. Additionally,
+ * default-constructed instances do not use a cryptographically random
+ * seed unless the {@linkplain System#getProperty system property}
+ * {@code java.util.secureRandomSeed} is set to {@code true}.
+ *
+ * @author Guy Steele
+ * @since 1.9
+ */
+public final class MRG32k3a extends AbstractArbitrarilyJumpableRng {
+
+ /*
+ * Implementation Overview.
+ *
+ * xxxx
+ *
+ * File organization: First the non-public methods that constitute
+ * the main algorithm, then the main public methods, followed by
+ * some custom spliterator classes needed for stream methods.
+ */
+
+ private final static double norm1 = 2.328306549295728e-10;
+ private final static double norm2 = 2.328318824698632e-10;
+ private final static double m1 = 4294967087.0;
+ private final static double m2 = 4294944443.0;
+ private final static double a12 = 1403580.0;
+ private final static double a13n = 810728.0;
+ private final static double a21 = 527612.0;
+ private final static double a23n = 1370589.0;
+ private final static int m1_deficit = 209;
+
+ // IllegalArgumentException messages
+ private static final String BadLogDistance = "logDistance must be non-negative and not greater than 192";
+
+ /**
+ * The per-instance state.
+ The seeds for s10, s11, s12 must be integers in [0, m1 - 1] and not all 0.
+ The seeds for s20, s21, s22 must be integers in [0, m2 - 1] and not all 0.
+ */
+ private double s10, s11, s12,
+ s20, s21, s22;
+
+ /**
+ * The seed generator for default constructors.
+ */
+ private static final AtomicLong defaultGen = new AtomicLong(RngSupport.initialSeed());
+
+ /*
+ 32-bits Random number generator U(0,1): MRG32k3a
+ Author: Pierre L'Ecuyer,
+ Source: Good Parameter Sets for Combined Multiple Recursive Random
+ Number Generators,
+ Shorter version in Operations Research,
+ 47, 1 (1999), 159--164.
+ ---------------------------------------------------------
+ */
+
+ private void nextState() {
+ /* Component 1 */
+ double p1 = a12 * s11 - a13n * s10;
+ double k1 = p1 / m1; p1 -= k1 * m1; if (p1 < 0.0) p1 += m1;
+ s10 = s11; s11 = s12; s12 = p1;
+ /* Component 2 */
+ double p2 = a21 * s22 - a23n * s20;
+ double k2 = p2 / m2; p2 -= k2 * m2; if (p2 < 0.0) p2 += m2;
+ s20 = s21; s21 = s22; s22 = p2;
+ }
+
+
+ /**
+ * The form of nextInt used by IntStream Spliterators.
+ * Exactly the same as long version, except for types.
+ *
+ * @param origin the least value, unless greater than bound
+ * @param bound the upper bound (exclusive), must not equal origin
+ * @return a pseudorandom value
+ */
+ protected int internalNextInt(int origin, int bound) {
+ if (origin < bound) {
+ final int n = bound - origin;
+ final int m = n - 1;
+ if (n > 0) {
+ int r;
+ for (int u = (int)nextDouble() >>> 1;
+ u + m + ((m1_deficit + 1) >>> 1) - (r = u % n) < 0;
+ u = (int)nextDouble() >>> 1)
+ ;
+ return (r + origin);
+ } else {
+ return RngSupport.boundedNextInt(this, origin, bound);
+ }
+ } else {
+ return nextInt();
+ }
+ }
+
+ protected int internalNextInt(int bound) {
+ // Specialize internalNextInt for origin == 0, bound > 0
+ final int n = bound;
+ final int m = n - 1;
+ int r;
+ for (int u = (int)nextDouble() >>> 1;
+ u + m + ((m1_deficit + 1) >>> 1) - (r = u % n) < 0;
+ u = (int)nextDouble() >>> 1)
+ ;
+ return r;
+ }
+
+ /**
+ * Constructor used by all others except default constructor.
+ * All arguments must be known to be nonnegative integral values.
+ */
+ private MRG32k3a(double s10, double s11, double s12,
+ double s20, double s21, double s22) {
+ this.s10 = s10; this.s11 = s11; this.s12 = s12;
+ this.s20 = s20; this.s21 = s21; this.s22 = s22;
+ if ((s10 == 0.0) && (s11 == 0.0) && (s12 == 0.0)) this.s10 = 12345.0;
+ if ((s20 == 0.0) && (s21 == 0.0) && (s22 == 0.0)) this.s20 = 12345.0;
+ }
+
+ /* ---------------- public methods ---------------- */
+
+ public MRG32k3a(int s10, int s11, int s12,
+ int s20, int s21, int s22) {
+ this(((double)(((long)s10) & 0x00000000ffffffffL)) % m1,
+ ((double)(((long)s11) & 0x00000000ffffffffL)) % m1,
+ ((double)(((long)s12) & 0x00000000ffffffffL)) % m1,
+ ((double)(((long)s20) & 0x00000000ffffffffL)) % m2,
+ ((double)(((long)s21) & 0x00000000ffffffffL)) % m2,
+ ((double)(((long)s22) & 0x00000000ffffffffL)) % m2);
+ }
+
+ /**
+ * Creates a new MRG32k3a instance using the specified
+ * initial seed. MRG32k3a instances created with the same
+ * seed in the same program generate identical sequences of values.
+ * An argument of 0 seeds the generator to a widely used initialization
+ * of MRG32k3a: all six state variables are set to 12345.
+ *
+ * @param seed the initial seed
+ */
+ public MRG32k3a(long seed) {
+ this((double)((seed & 0x7FF) + 12345),
+ (double)(((seed >>> 11) & 0x7FF) + 12345),
+ (double)(((seed >>> 22) & 0x7FF) + 12345),
+ (double)(((seed >>> 33) & 0x7FF) + 12345),
+ (double)(((seed >>> 44) & 0x7FF) + 12345),
+ (double)((seed >>> 55) + 12345));
+ }
+
+ /**
+ * Creates a new MRG32k3a instance that is likely to
+ * generate sequences of values that are statistically independent
+ * of those of any other instances in the current program; and
+ * may, and typically does, vary across program invocations.
+ */
+ public MRG32k3a() {
+ this(defaultGen.getAndAdd(RngSupport.GOLDEN_RATIO_64));
+ }
+
+ /**
+ * Creates a new instance of {@code Xoshiro256StarStar} using the specified array of
+ * initial seed bytes. Instances of {@code Xoshiro256StarStar} created with the same
+ * seed array in the same program execution generate identical sequences of values.
+ *
+ * @param seed the initial seed
+ */
+ public MRG32k3a(byte[] seed) {
+ // Convert the seed to 6 int values.
+ int[] data = RngSupport.convertSeedBytesToInts(seed, 6, 0);
+ int s10 = data[0], s11 = data[1], s12 = data[2];
+ int s20 = data[3], s21 = data[4], s22 = data[5];
+ this.s10 = ((double)(((long)s10) & 0x00000000ffffffffL)) % m1;
+ this.s11 = ((double)(((long)s11) & 0x00000000ffffffffL)) % m1;
+ this.s12 = ((double)(((long)s12) & 0x00000000ffffffffL)) % m1;
+ this.s20 = ((double)(((long)s20) & 0x00000000ffffffffL)) % m2;
+ this.s21 = ((double)(((long)s21) & 0x00000000ffffffffL)) % m2;
+ this.s22 = ((double)(((long)s22) & 0x00000000ffffffffL)) % m2;
+ if ((s10 == 0.0) && (s11 == 0.0) && (s12 == 0.0)) this.s10 = 12345.0;
+ if ((s20 == 0.0) && (s21 == 0.0) && (s22 == 0.0)) this.s20 = 12345.0;
+ }
+
+ public MRG32k3a copy() { return new MRG32k3a(s10, s11, s12, s20, s21, s22); }
+
+ /**
+ * Returns a pseudorandom {@code double} value between zero
+ * (exclusive) and one (exclusive).
+ *
+ * @return a pseudorandom {@code double} value between zero
+ * (exclusive) and one (exclusive)
+ */
+ public double nextOpenDouble() {
+ nextState();
+ double p1 = s12, p2 = s22;
+ if (p1 <= p2)
+ return ((p1 - p2 + m1) * norm1);
+ else
+ return ((p1 - p2) * norm1);
+ }
+
+ /**
+ * Returns a pseudorandom {@code double} value between zero
+ * (inclusive) and one (exclusive).
+ *
+ * @return a pseudorandom {@code double} value between zero
+ * (inclusive) and one (exclusive)
+ */
+ public double nextDouble() {
+ nextState();
+ double p1 = s12, p2 = s22;
+ final double p = p1 * norm1 - p2 * norm2;
+ if (p < 0.0) return (p + 1.0);
+ else return p;
+ }
+
+
+ /**
+ * Returns a pseudorandom {@code float} value between zero
+ * (inclusive) and one (exclusive).
+ *
+ * @return a pseudorandom {@code float} value between zero
+ * (inclusive) and one (exclusive)
+ */
+ public float nextFloat() {
+ return (float)nextDouble();
+ }
+
+ /**
+ * Returns a pseudorandom {@code int} value.
+ *
+ * @return a pseudorandom {@code int} value
+ */
+ public int nextInt() {
+ return (internalNextInt(0x10000) << 16) | internalNextInt(0x10000);
+ }
+
+ /**
+ * Returns a pseudorandom {@code long} value.
+ *
+ * @return a pseudorandom {@code long} value
+ */
+
+ public long nextLong() {
+ return (((long)internalNextInt(0x200000) << 43) |
+ ((long)internalNextInt(0x200000) << 22) |
+ ((long)internalNextInt(0x400000)));
+ }
+
+ // Period is (m1**3 - 1)(m2**3 - 1)/2, or approximately 2**191.
+ static BigInteger calculateThePeriod() {
+ BigInteger bigm1 = BigInteger.valueOf((long)m1);
+ BigInteger bigm2 = BigInteger.valueOf((long)m2);
+ BigInteger t1 = bigm1.multiply(bigm1).multiply(bigm1).subtract(BigInteger.ONE);
+ BigInteger t2 = bigm2.multiply(bigm2).multiply(bigm2).subtract(BigInteger.ONE);
+ return t1.shiftRight(1).multiply(t2);
+ }
+ static final BigInteger thePeriod = calculateThePeriod();
+ public BigInteger period() { return thePeriod; }
+
+ // Jump and leap distances recommended in Section 1.3 of this paper:
+ // Pierre L'Ecuyer, Richard Simard, E. Jack Chen, and W. David Kelton.
+ // An Object-Oriented Random-Number Package with Many Long Streams and Substreams.
+ // Operations Research 50, 6 (Nov--Dec 2002), 1073--1075.
+
+ public double defaultJumpDistance() { return 0x1.0p76; } // 2**76
+ public double defaultLeapDistance() { return 0x1.0p127; } // 2**127
+
+ public void jump(double distance) {
+ if (distance < 0.0 || Double.isInfinite(distance) || distance != Math.floor(distance))
+ throw new IllegalArgumentException("jump distance must be a nonnegative finite integer");
+ // We will compute a jump transformation (s => M s) for each LCG.
+ // We initialize each transformation to the identity transformation.
+ // Each will be turned into the d'th power of the corresponding base transformation.
+ long m1_00 = 1, m1_01 = 0, m1_02 = 0,
+ m1_10 = 0, m1_11 = 1, m1_12 = 0,
+ m1_20 = 0, m1_21 = 0, m1_22 = 1;
+ long m2_00 = 1, m2_01 = 0, m2_02 = 0,
+ m2_10 = 0, m2_11 = 1, m2_12 = 0,
+ m2_20 = 0, m2_21 = 0, m2_22 = 1;
+ // These are the base transformations, which will be repeatedly squared,
+ // and composed with the computed transformations for each 1-bit in distance.
+ long t1_00 = 0, t1_01 = 1, t1_02 = 0,
+ t1_10 = 0, t1_11 = 0, t1_12 = 1,
+ t1_20 = -(long)a13n, t1_21 = (long)a12, t1_22 = 0;
+ long t2_00 = 0, t2_01 = 1, t2_02 = 0,
+ t2_10 = 0, t2_11 = 0, t2_12 = 1,
+ t2_20 = -(long)a23n, t2_21 = (long)a21, t2_22 = 0;
+ while (distance > 0.0) {
+ final double dhalf = 0.5 * distance;
+ if (Math.floor(dhalf) != dhalf) {
+ // distance is odd: accumulate current squaring
+ final long n1_00 = m1_00 * t1_00 + m1_01 * t1_10 + m1_02 * t1_20;
+ final long n1_01 = m1_00 * t1_01 + m1_01 * t1_11 + m1_02 * t1_21;
+ final long n1_02 = m1_00 * t1_02 + m1_01 * t1_12 + m1_02 * t1_22;
+ final long n1_10 = m1_10 * t1_00 + m1_11 * t1_10 + m1_12 * t1_20;
+ final long n1_11 = m1_10 * t1_01 + m1_11 * t1_11 + m1_12 * t1_21;
+ final long n1_12 = m1_10 * t1_02 + m1_11 * t1_12 + m1_12 * t1_22;
+ final long n1_20 = m1_20 * t1_00 + m1_21 * t1_10 + m1_22 * t1_20;
+ final long n1_21 = m1_20 * t1_01 + m1_21 * t1_11 + m1_22 * t1_21;
+ final long n1_22 = m1_20 * t1_02 + m1_21 * t1_12 + m1_22 * t1_22;
+ m1_00 = Math.floorMod(n1_00, (long)m1);
+ m1_01 = Math.floorMod(n1_01, (long)m1);
+ m1_02 = Math.floorMod(n1_02, (long)m1);
+ m1_10 = Math.floorMod(n1_10, (long)m1);
+ m1_11 = Math.floorMod(n1_11, (long)m1);
+ m1_12 = Math.floorMod(n1_12, (long)m1);
+ m1_20 = Math.floorMod(n1_20, (long)m1);
+ m1_21 = Math.floorMod(n1_21, (long)m1);
+ m1_22 = Math.floorMod(n1_22, (long)m1);
+ final long n2_00 = m2_00 * t2_00 + m2_01 * t2_10 + m2_02 * t2_20;
+ final long n2_01 = m2_00 * t2_01 + m2_01 * t2_11 + m2_02 * t2_21;
+ final long n2_02 = m2_00 * t2_02 + m2_01 * t2_12 + m2_02 * t2_22;
+ final long n2_10 = m2_10 * t2_00 + m2_11 * t2_10 + m2_12 * t2_20;
+ final long n2_11 = m2_10 * t2_01 + m2_11 * t2_11 + m2_12 * t2_21;
+ final long n2_12 = m2_10 * t2_02 + m2_11 * t2_12 + m2_12 * t2_22;
+ final long n2_20 = m2_20 * t2_00 + m2_21 * t2_10 + m2_22 * t2_20;
+ final long n2_21 = m2_20 * t2_01 + m2_21 * t2_11 + m2_22 * t2_21;
+ final long n2_22 = m2_20 * t2_02 + m2_21 * t2_12 + m2_22 * t2_22;
+ m2_00 = Math.floorMod(n2_00, (long)m2);
+ m2_01 = Math.floorMod(n2_01, (long)m2);
+ m2_02 = Math.floorMod(n2_02, (long)m2);
+ m2_10 = Math.floorMod(n2_10, (long)m2);
+ m2_11 = Math.floorMod(n2_11, (long)m2);
+ m2_12 = Math.floorMod(n2_12, (long)m2);
+ m2_20 = Math.floorMod(n2_20, (long)m2);
+ m2_21 = Math.floorMod(n2_21, (long)m2);
+ m2_22 = Math.floorMod(n2_22, (long)m2);
+ }
+ // Square the base transformations.
+ {
+ final long z1_00 = m1_00 * m1_00 + m1_01 * m1_10 + m1_02 * m1_20;
+ final long z1_01 = m1_00 * m1_01 + m1_01 * m1_11 + m1_02 * m1_21;
+ final long z1_02 = m1_00 * m1_02 + m1_01 * m1_12 + m1_02 * m1_22;
+ final long z1_10 = m1_10 * m1_00 + m1_11 * m1_10 + m1_12 * m1_20;
+ final long z1_11 = m1_10 * m1_01 + m1_11 * m1_11 + m1_12 * m1_21;
+ final long z1_12 = m1_10 * m1_02 + m1_11 * m1_12 + m1_12 * m1_22;
+ final long z1_20 = m1_20 * m1_00 + m1_21 * m1_10 + m1_22 * m1_20;
+ final long z1_21 = m1_20 * m1_01 + m1_21 * m1_11 + m1_22 * m1_21;
+ final long z1_22 = m1_20 * m1_02 + m1_21 * m1_12 + m1_22 * m1_22;
+ m1_00 = Math.floorMod(z1_00, (long)m1);
+ m1_01 = Math.floorMod(z1_01, (long)m1);
+ m1_02 = Math.floorMod(z1_02, (long)m1);
+ m1_10 = Math.floorMod(z1_10, (long)m1);
+ m1_11 = Math.floorMod(z1_11, (long)m1);
+ m1_12 = Math.floorMod(z1_12, (long)m1);
+ m1_20 = Math.floorMod(z1_20, (long)m1);
+ m1_21 = Math.floorMod(z1_21, (long)m1);
+ m1_22 = Math.floorMod(z1_22, (long)m1);
+ final long z2_00 = m2_00 * m2_00 + m2_01 * m2_10 + m2_02 * m2_20;
+ final long z2_01 = m2_00 * m2_01 + m2_01 * m2_11 + m2_02 * m2_21;
+ final long z2_02 = m2_00 * m2_02 + m2_01 * m2_12 + m2_02 * m2_22;
+ final long z2_10 = m2_10 * m2_00 + m2_11 * m2_10 + m2_12 * m2_20;
+ final long z2_11 = m2_10 * m2_01 + m2_11 * m2_11 + m2_12 * m2_21;
+ final long z2_12 = m2_10 * m2_02 + m2_11 * m2_12 + m2_12 * m2_22;
+ final long z2_20 = m2_20 * m2_00 + m2_21 * m2_10 + m2_22 * m2_20;
+ final long z2_21 = m2_20 * m2_01 + m2_21 * m2_11 + m2_22 * m2_21;
+ final long z2_22 = m2_20 * m2_02 + m2_21 * m2_12 + m2_22 * m2_22;
+ m2_00 = Math.floorMod(z2_00, (long)m2);
+ m2_01 = Math.floorMod(z2_01, (long)m2);
+ m2_02 = Math.floorMod(z2_02, (long)m2);
+ m2_10 = Math.floorMod(z2_10, (long)m2);
+ m2_11 = Math.floorMod(z2_11, (long)m2);
+ m2_12 = Math.floorMod(z2_12, (long)m2);
+ m2_20 = Math.floorMod(z2_20, (long)m2);
+ m2_21 = Math.floorMod(z2_21, (long)m2);
+ m2_22 = Math.floorMod(z2_22, (long)m2);
+ }
+ // Divide distance by 2.
+ distance = dhalf;
+ }
+ final long w10 = m1_00 * (long)s10 + m1_01 * (long)s11 + m1_02 * (long)s12;
+ final long w11 = m1_10 * (long)s10 + m1_11 * (long)s11 + m1_12 * (long)s12;
+ final long w12 = m1_20 * (long)s10 + m1_21 * (long)s11 + m1_22 * (long)s12;
+ s10 = Math.floorMod(w10, (long)m1);
+ s11 = Math.floorMod(w11, (long)m1);
+ s12 = Math.floorMod(w12, (long)m1);
+ final long w20 = m2_00 * (long)s20 + m2_01 * (long)s21 + m2_02 * (long)s22;
+ final long w21 = m2_10 * (long)s20 + m2_11 * (long)s21 + m2_12 * (long)s22;
+ final long w22 = m2_20 * (long)s20 + m2_21 * (long)s21 + m2_22 * (long)s22;
+ s20 = Math.floorMod(w20, (long)m2);
+ s21 = Math.floorMod(w21, (long)m2);
+ s22 = Math.floorMod(w22, (long)m2);
+ }
+
+ /**
+ * Alter the state of this pseudorandom number generator so as to
+ * jump forward a distance equal to 2{@code logDistance}
+ * within its state cycle.
+ *
+ * @param logDistance the base-2 logarithm of the distance to jump
+ * forward within the state cycle. Must be non-negative and
+ * not greater than 192.
+ * @throws IllegalArgumentException if {@code logDistance} is
+ * less than zero or 2{@code logDistance} is
+ * greater than the period of this generator
+ */
+ public void jumpPowerOfTwo(int logDistance) {
+ if (logDistance < 0 || logDistance > 192)
+ throw new IllegalArgumentException(BadLogDistance);
+ jump(Math.scalb(1.0, logDistance));
+ }
+
+}
diff -r c646b256fbcc -r 6d87e9f7a1ec newrandom/Random.java
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/newrandom/Random.java Thu May 23 16:45:56 2019 -0400
@@ -0,0 +1,564 @@
+/*
+ * Copyright (c) 1995, 2013, 2019, Oracle and/or its affiliates. All rights reserved.
+ * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ */
+
+// package java.util;
+
+import java.io.*;
+import java.math.BigInteger;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.DoubleConsumer;
+import java.util.function.IntConsumer;
+import java.util.function.LongConsumer;
+import java.util.stream.DoubleStream;
+import java.util.stream.IntStream;
+import java.util.stream.LongStream;
+import java.util.stream.StreamSupport;
+
+import sun.misc.Unsafe;
+
+/**
+ * An instance of this class is used to generate a stream of
+ * pseudorandom numbers. The class uses a 48-bit seed, which is
+ * modified using a linear congruential formula. (See Donald Knuth,
+ * The Art of Computer Programming, Volume 2, Section 3.2.1.)
+ *
+ * If two instances of {@code Random} are created with the same
+ * seed, and the same sequence of method calls is made for each, they
+ * will generate and return identical sequences of numbers. In order to
+ * guarantee this property, particular algorithms are specified for the
+ * class {@code Random}. Java implementations must use all the algorithms
+ * shown here for the class {@code Random}, for the sake of absolute
+ * portability of Java code. However, subclasses of class {@code Random}
+ * are permitted to use other algorithms, so long as they adhere to the
+ * general contracts for all the methods.
+ *
+ * The algorithms implemented by class {@code Random} use a
+ * {@code protected} utility method that on each invocation can supply
+ * up to 32 pseudorandomly generated bits.
+ *
+ * Many applications will find the method {@link Math#random} simpler to use.
+ *
+ * Instances of {@code java.util.Random} are threadsafe.
+ * However, the concurrent use of the same {@code java.util.Random}
+ * instance across threads may encounter contention and consequent
+ * poor performance. Consider instead using
+ * {@link java.util.concurrent.ThreadLocalRandom} in multithreaded
+ * designs.
+ *
+ * Instances of {@code java.util.Random} are not cryptographically
+ * secure. Consider instead using {@link java.security.SecureRandom} to
+ * get a cryptographically secure pseudo-random number generator for use
+ * by security-sensitive applications.
+ *
+ * @author Frank Yellin
+ * @since 1.0
+ */
+public
+ class Random extends AbstractSharedRng implements java.io.Serializable {
+ /** use serialVersionUID from JDK 1.1 for interoperability */
+ static final long serialVersionUID = 3905348978240129619L;
+
+ /**
+ * The internal state associated with this pseudorandom number generator.
+ * (The specs for the methods in this class describe the ongoing
+ * computation of this value.)
+ */
+ private final AtomicLong seed;
+
+ private static final long multiplier = 0x5DEECE66DL;
+ private static final long addend = 0xBL;
+ private static final long mask = (1L << 48) - 1;
+
+ private static final double DOUBLE_UNIT = 0x1.0p-53; // 1.0 / (1L << 53)
+
+ // IllegalArgumentException messages
+ static final String BadBound = "bound must be positive";
+ static final String BadRange = "bound must be greater than origin";
+ static final String BadSize = "size must be non-negative";
+
+ /**
+ * Creates a new random number generator. This constructor sets
+ * the seed of the random number generator to a value very likely
+ * to be distinct from any other invocation of this constructor.
+ */
+ public Random() {
+ this(seedUniquifier() ^ System.nanoTime());
+ }
+
+ private static long seedUniquifier() {
+ // L'Ecuyer, "Tables of Linear Congruential Generators of
+ // Different Sizes and Good Lattice Structure", 1999
+ for (;;) {
+ long current = seedUniquifier.get();
+ long next = current * 181783497276652981L;
+ if (seedUniquifier.compareAndSet(current, next))
+ return next;
+ }
+ }
+
+ private static final AtomicLong seedUniquifier
+ = new AtomicLong(8682522807148012L);
+
+ /**
+ * Creates a new random number generator using a single {@code long} seed.
+ * The seed is the initial value of the internal state of the pseudorandom
+ * number generator which is maintained by method {@link #next}.
+ *
+ * The invocation {@code new Random(seed)} is equivalent to:
+ * The implementation of {@code setSeed} by class {@code Random}
+ * happens to use only 48 bits of the given seed. In general, however,
+ * an overriding method may use all 64 bits of the {@code long}
+ * argument as a seed value.
+ *
+ * @param seed the initial seed
+ */
+ synchronized public void setSeed(long seed) {
+ this.seed.set(initialScramble(seed));
+ haveNextNextGaussian = false;
+ }
+
+ /**
+ * Generates the next pseudorandom number. Subclasses should
+ * override this, as this is used by all other methods.
+ *
+ * The general contract of {@code next} is that it returns an
+ * {@code int} value and if the argument {@code bits} is between
+ * {@code 1} and {@code 32} (inclusive), then that many low-order
+ * bits of the returned value will be (approximately) independently
+ * chosen bit values, each of which is (approximately) equally
+ * likely to be {@code 0} or {@code 1}. The method {@code next} is
+ * implemented by class {@code Random} by atomically updating the seed to
+ * The method {@code nextBytes} is implemented by class {@code Random}
+ * as if by:
+ * The method {@code nextInt} is implemented by class {@code Random}
+ * as if by:
+ * The method {@code nextLong} is implemented by class {@code Random}
+ * as if by:
+ * The method {@code nextBoolean} is implemented by class {@code Random}
+ * as if by:
+ * The general contract of {@code nextFloat} is that one
+ * {@code float} value, chosen (approximately) uniformly from the
+ * range {@code 0.0f} (inclusive) to {@code 1.0f} (exclusive), is
+ * pseudorandomly generated and returned. All 224 possible
+ * {@code float} values of the form m x 2-24,
+ * where m is a positive integer less than 224, are
+ * produced with (approximately) equal probability.
+ *
+ * The method {@code nextFloat} is implemented by class {@code Random}
+ * as if by:
+ * The hedge "approximately" is used in the foregoing description only
+ * because the next method is only approximately an unbiased source of
+ * independently chosen bits. If it were a perfect source of randomly
+ * chosen bits, then the algorithm shown would choose {@code float}
+ * values from the stated range with perfect uniformity.
+ * [In early versions of Java, the result was incorrectly calculated as:
+ * The general contract of {@code nextDouble} is that one
+ * {@code double} value, chosen (approximately) uniformly from the
+ * range {@code 0.0d} (inclusive) to {@code 1.0d} (exclusive), is
+ * pseudorandomly generated and returned.
+ *
+ * The method {@code nextDouble} is implemented by class {@code Random}
+ * as if by:
+ * The hedge "approximately" is used in the foregoing description only
+ * because the {@code next} method is only approximately an unbiased
+ * source of independently chosen bits. If it were a perfect source of
+ * randomly chosen bits, then the algorithm shown would choose
+ * {@code double} values from the stated range with perfect uniformity.
+ * [In early versions of Java, the result was incorrectly calculated as:
+ *
+ * The general contract of {@code nextGaussian} is that one
+ * {@code double} value, chosen from (approximately) the usual
+ * normal distribution with mean {@code 0.0} and standard deviation
+ * {@code 1.0}, is pseudorandomly generated and returned.
+ *
+ * The method {@code nextGaussian} is implemented by class
+ * {@code Random} as if by a threadsafe version of the following:
+ * Ideally, given an implicitly or explicitly specified range of values,
+ * each value would be chosen independently and uniformly from that range.
+ * In practice, one may have to settle for some approximation to independence
+ * and uniformity.
+ *
+ * In the case of {@code int}, {@code long}, and {@code Boolean}
+ * values, if there is no explicit specification of range, then the
+ * range includes all possible values of the type. In the case of
+ * {@code float} and {@code double} values, a value is always chosen
+ * from the set of 2 Each method that returns a stream produces a stream of values each of
+ * which is chosen in the same manner as for a method that
+ * returns a single (pseudo)randomly chosen value. For example, if {@code r}
+ * implements {@code Rng}, then the method call {@code r.ints(100)} returns
+ * a stream of 100 {@code int} values. These are not necessarily the exact
+ * same values that would have been returned if instead {@code r.nextInt()}
+ * had been called 100 times; all that is guaranteed is that each value in
+ * the stream is chosen in a similar (pseudo)random manner from the same range.
+ *
+ * Every object that implements the {@code Rng} interface is assumed
+ * to contain a finite amount of state. Using such an object to
+ * generate a pseudorandomly chosen value alters its state. The
+ * number of distinct possible states of such an object is called its
+ * As a rule, objects that implement the {@code Rng} interface need not
+ * be thread-safe. It is recommended that multithreaded applications
+ * use either {@code ThreadLocalRandom} or (preferably) pseudorandom
+ * number generators that implement the {@code SplittableRng} or
+ * {@code JumpableRng} interface.
+
+ * To implement this interface, a class only needs to provide concrete
+ * definitions for the methods {@code nextLong()} and {@code period()}.
+ * Default implementations are provided for all other methods
+ * (but it may be desirable to override some of them, especially
+ * {@code nextInt()} if the underlying algorithm is {@code int}-based).
+ * Moerover, it may be preferable instead to implement another interface
+ * such as {@link java.util.JumpableRng} or {@link java.util.LeapableRng},
+ * or to extend an abstract class such as {@link java.util.AbstractSplittableRng}
+ * or {@link java.util.AbstractArbitrarilyJumpableRng}.
+ *
+ * Objects that implement {@code java.util.Rng} are typically
+ * not cryptographically secure. Consider instead using
+ * {@link java.security.SecureRandom} to get a cryptographically
+ * secure pseudorandom number generator for use by
+ * security-sensitive applications. Note, however, that
+ * {@code java.security.SecureRandom} does implement the {@code Rng}
+ * interface, so that instances of {@code java.security.SecureRandom}
+ * may be used interchangeably with other types of pseudorandom
+ * generators in applications that do not require a secure generator.
+ *
+ * @author Guy Steele
+ * @since 1.9
+ */
+
+interface Rng {
+
+ /**
+ * Returns an effectively unlimited stream of pseudorandomly chosen
+ * {@code double} values.
+ *
+ * @implNote It is permitted to implement this method in a manner
+ * equivalent to {@code doubles(Long.MAX_VALUE)}.
+ *
+ * @implNote The default implementation produces a sequential stream
+ * that repeatedly calls {@code nextDouble()}.
+ *
+ * @return a stream of pseudorandomly chosen {@code double} values
+ */
+
+ default DoubleStream doubles() {
+ return DoubleStream.generate(this::nextDouble).sequential();
+ }
+
+ /**
+ * Returns an effectively unlimited stream of pseudorandomly chosen
+ * {@code double} values, where each value is between the specified
+ * origin (inclusive) and the specified bound (exclusive).
+ *
+ * @implNote It is permitted to implement this method in a manner
+ * equivalent to
+ * {@code doubles(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
+ *
+ * @implNote The default implementation produces a sequential stream
+ * that repeatedly calls {@code nextDouble(randomNumberOrigin, randomNumberBound)}.
+ *
+ * @param randomNumberOrigin the least value that can be produced
+ * @param randomNumberBound the upper bound (exclusive) for each value produced
+ * @return a stream of pseudorandomly chosen {@code double} values, each between
+ * the specified origin (inclusive) and the specified bound (exclusive)
+ * @throws IllegalArgumentException if {@code randomNumberOrigin}
+ * is greater than or equal to {@code randomNumberBound}
+ */
+ default DoubleStream doubles(double randomNumberOrigin, double randomNumberBound) {
+ RngSupport.checkRange(randomNumberOrigin, randomNumberBound);
+ return DoubleStream.generate(() -> nextDouble(randomNumberOrigin, randomNumberBound)).sequential();
+ }
+
+ /**
+ * Returns a stream producing the given {@code streamSize} number of
+ * pseudorandomly chosen {@code double} values.
+ *
+ * @implNote The default implementation produces a sequential stream
+ * that repeatedly calls {@code nextDouble()}.
+ *
+ * @param streamSize the number of values to generate
+ * @return a stream of pseudorandomly chosen {@code double} values
+ * @throws IllegalArgumentException if {@code streamSize} is
+ * less than zero
+ */
+ default DoubleStream doubles(long streamSize) {
+ RngSupport.checkStreamSize(streamSize);
+ return doubles().limit(streamSize);
+ }
+
+ /**
+ * Returns a stream producing the given {@code streamSize} number of
+ * pseudorandomly chosen {@code double} values, where each value is between
+ * the specified origin (inclusive) and the specified bound (exclusive).
+ *
+ * @implNote The default implementation produces a sequential stream
+ * that repeatedly calls {@code nextDouble(randomNumberOrigin, randomNumberBound)}.
+ *
+ * @param streamSize the number of values to generate
+ * @param randomNumberOrigin the least value that can be produced
+ * @param randomNumberBound the upper bound (exclusive) for each value produced
+ * @return a stream of pseudorandomly chosen {@code double} values, each between
+ * the specified origin (inclusive) and the specified bound (exclusive)
+ * @throws IllegalArgumentException if {@code streamSize} is
+ * less than zero, or {@code randomNumberOrigin}
+ * is greater than or equal to {@code randomNumberBound}
+ */
+ default DoubleStream doubles(long streamSize, double randomNumberOrigin,
+ double randomNumberBound) {
+ RngSupport.checkStreamSize(streamSize);
+ RngSupport.checkRange(randomNumberOrigin, randomNumberBound);
+ return doubles(randomNumberOrigin, randomNumberBound).limit(streamSize);
+ }
+
+ /**
+ * Returns an effectively unlimited stream of pseudorandomly chosen
+ * {@code int} values.
+ *
+ * @implNote It is permitted to implement this method in a manner
+ * equivalent to {@code ints(Long.MAX_VALUE)}.
+ *
+ * @implNote The default implementation produces a sequential stream
+ * that repeatedly calls {@code nextInt()}.
+ *
+ * @return a stream of pseudorandomly chosen {@code int} values
+ */
+
+ default IntStream ints() {
+ return IntStream.generate(this::nextInt).sequential();
+ }
+
+ /**
+ * Returns an effectively unlimited stream of pseudorandomly chosen
+ * {@code int} values, where each value is between the specified
+ * origin (inclusive) and the specified bound (exclusive).
+ *
+ * @implNote It is permitted to implement this method in a manner
+ * equivalent to
+ * {@code ints(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
+ *
+ * @implNote The default implementation produces a sequential stream
+ * that repeatedly calls {@code nextInt(randomNumberOrigin, randomNumberBound)}.
+ *
+ * @param randomNumberOrigin the least value that can be produced
+ * @param randomNumberBound the upper bound (exclusive) for each value produced
+ * @return a stream of pseudorandomly chosen {@code int} values, each between
+ * the specified origin (inclusive) and the specified bound (exclusive)
+ * @throws IllegalArgumentException if {@code randomNumberOrigin}
+ * is greater than or equal to {@code randomNumberBound}
+ */
+ default IntStream ints(int randomNumberOrigin, int randomNumberBound) {
+ RngSupport.checkRange(randomNumberOrigin, randomNumberBound);
+ return IntStream.generate(() -> nextInt(randomNumberOrigin, randomNumberBound)).sequential();
+ }
+
+ /**
+ * Returns a stream producing the given {@code streamSize} number of
+ * pseudorandomly chosen {@code int} values.
+ *
+ * @implNote The default implementation produces a sequential stream
+ * that repeatedly calls {@code nextInt()}.
+ *
+ * @param streamSize the number of values to generate
+ * @return a stream of pseudorandomly chosen {@code int} values
+ * @throws IllegalArgumentException if {@code streamSize} is
+ * less than zero
+ */
+ default IntStream ints(long streamSize) {
+ RngSupport.checkStreamSize(streamSize);
+ return ints().limit(streamSize);
+ }
+
+ /**
+ * Returns a stream producing the given {@code streamSize} number of
+ * pseudorandomly chosen {@code int} values, where each value is between
+ * the specified origin (inclusive) and the specified bound (exclusive).
+ *
+ * @implNote The default implementation produces a sequential stream
+ * that repeatedly calls {@code nextInt(randomNumberOrigin, randomNumberBound)}.
+ *
+ * @param streamSize the number of values to generate
+ * @param randomNumberOrigin the least value that can be produced
+ * @param randomNumberBound the upper bound (exclusive) for each value produced
+ * @return a stream of pseudorandomly chosen {@code int} values, each between
+ * the specified origin (inclusive) and the specified bound (exclusive)
+ * @throws IllegalArgumentException if {@code streamSize} is
+ * less than zero, or {@code randomNumberOrigin}
+ * is greater than or equal to {@code randomNumberBound}
+ */
+ default IntStream ints(long streamSize, int randomNumberOrigin,
+ int randomNumberBound) {
+ RngSupport.checkStreamSize(streamSize);
+ RngSupport.checkRange(randomNumberOrigin, randomNumberBound);
+ return ints(randomNumberOrigin, randomNumberBound).limit(streamSize);
+ }
+
+ /**
+ * Returns an effectively unlimited stream of pseudorandomly chosen
+ * {@code long} values.
+ *
+ * @implNote It is permitted to implement this method in a manner
+ * equivalent to {@code longs(Long.MAX_VALUE)}.
+ *
+ * @implNote The default implementation produces a sequential stream
+ * that repeatedly calls {@code nextLong()}.
+ *
+ * @return a stream of pseudorandomly chosen {@code long} values
+ */
+
+ default LongStream longs() {
+ return LongStream.generate(this::nextLong).sequential();
+ }
+
+ /**
+ * Returns an effectively unlimited stream of pseudorandomly chosen
+ * {@code long} values, where each value is between the specified
+ * origin (inclusive) and the specified bound (exclusive).
+ *
+ * @implNote It is permitted to implement this method in a manner
+ * equivalent to
+ * {@code longs(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
+ *
+ * @implNote The default implementation produces a sequential stream
+ * that repeatedly calls {@code nextLong(randomNumberOrigin, randomNumberBound)}.
+ *
+ * @param randomNumberOrigin the least value that can be produced
+ * @param randomNumberBound the upper bound (exclusive) for each value produced
+ * @return a stream of pseudorandomly chosen {@code long} values, each between
+ * the specified origin (inclusive) and the specified bound (exclusive)
+ * @throws IllegalArgumentException if {@code randomNumberOrigin}
+ * is greater than or equal to {@code randomNumberBound}
+ */
+ default LongStream longs(long randomNumberOrigin, long randomNumberBound) {
+ RngSupport.checkRange(randomNumberOrigin, randomNumberBound);
+ return LongStream.generate(() -> nextLong(randomNumberOrigin, randomNumberBound)).sequential();
+ }
+
+ /**
+ * Returns a stream producing the given {@code streamSize} number of
+ * pseudorandomly chosen {@code long} values.
+ *
+ * @implNote The default implementation produces a sequential stream
+ * that repeatedly calls {@code nextLong()}.
+ *
+ * @param streamSize the number of values to generate
+ * @return a stream of pseudorandomly chosen {@code long} values
+ * @throws IllegalArgumentException if {@code streamSize} is
+ * less than zero
+ */
+ default LongStream longs(long streamSize) {
+ RngSupport.checkStreamSize(streamSize);
+ return longs().limit(streamSize);
+ }
+
+ /**
+ * Returns a stream producing the given {@code streamSize} number of
+ * pseudorandomly chosen {@code long} values, where each value is between
+ * the specified origin (inclusive) and the specified bound (exclusive).
+ *
+ * @implNote The default implementation produces a sequential stream
+ * that repeatedly calls {@code nextLong(randomNumberOrigin, randomNumberBound)}.
+ *
+ * @param streamSize the number of values to generate
+ * @param randomNumberOrigin the least value that can be produced
+ * @param randomNumberBound the upper bound (exclusive) for each value produced
+ * @return a stream of pseudorandomly chosen {@code long} values, each between
+ * the specified origin (inclusive) and the specified bound (exclusive)
+ * @throws IllegalArgumentException if {@code streamSize} is
+ * less than zero, or {@code randomNumberOrigin}
+ * is greater than or equal to {@code randomNumberBound}
+ */
+ default LongStream longs(long streamSize, long randomNumberOrigin,
+ long randomNumberBound) {
+ RngSupport.checkStreamSize(streamSize);
+ RngSupport.checkRange(randomNumberOrigin, randomNumberBound);
+ return longs(randomNumberOrigin, randomNumberBound).limit(streamSize);
+ }
+
+ /**
+ * Returns a pseudorandomly chosen {@code boolean} value.
+ *
+ * The default implementation tests the high-order bit (sign bit)
+ * of a value produced by {@code nextInt()}, on the grounds
+ * that some algorithms for pseudorandom number generation
+ * produce values whose high-order bits have better
+ * statistical quality than the low-order bits.
+ *
+ * @return a pseudorandomly chosen {@code boolean} value
+ */
+ default boolean nextBoolean() {
+ return nextInt() < 0;
+ }
+
+ /**
+ * Returns a pseudorandom {@code float} value between zero
+ * (inclusive) and one (exclusive).
+ *
+ * The default implementation uses the 24 high-order bits
+ * from a call to {@code nextInt()}.
+ *
+ * @return a pseudorandom {@code float} value between zero
+ * (inclusive) and one (exclusive)
+ */
+ default float nextFloat() {
+ return (nextInt() >>> 8) * 0x1.0p-24f;
+ }
+
+ /**
+ * Returns a pseudorandomly chosen {@code float} value between zero
+ * (inclusive) and the specified bound (exclusive).
+ *
+ * @implNote The default implementation simply calls
+ * {@code RngSupport.checkBound(bound)} and then
+ * {@code RngSupport.boundedNextFloat(this, bound)}.
+ *
+ * @param bound the upper bound (exclusive) for the returned value.
+ * Must be positive and finite
+ * @return a pseudorandomly chosen {@code float} value between
+ * zero (inclusive) and the bound (exclusive)
+ * @throws IllegalArgumentException if {@code bound} is not
+ * positive and finite
+ */
+ default float nextFloat(float bound) {
+ RngSupport.checkBound(bound);
+ return RngSupport.boundedNextFloat(this, bound);
+ }
+
+ /**
+ * Returns a pseudorandomly chosen {@code float} value between the
+ * specified origin (inclusive) and the specified bound (exclusive).
+ *
+ * @implNote The default implementation simply calls
+ * {@code RngSupport.checkRange(origin, bound)} and then
+ * {@code RngSupport.boundedNextFloat(this, origin, bound)}.
+ *
+ * @param origin the least value that can be returned
+ * @param bound the upper bound (exclusive)
+ * @return a pseudorandomly chosen {@code float} value between the
+ * origin (inclusive) and the bound (exclusive)
+ * @throws IllegalArgumentException unless {@code origin} is finite,
+ * {@code bound} is finite, and {@code origin} is less than
+ * {@code bound}
+ */
+ default float nextFloat(float origin, float bound) {
+ RngSupport.checkRange(origin, bound);
+ return RngSupport.boundedNextFloat(this, origin, bound);
+ }
+
+ /**
+ * Returns a pseudorandom {@code double} value between zero
+ * (inclusive) and one (exclusive).
+ *
+ * The default implementation uses the 53 high-order bits
+ * from a call to {@code nextLong()}.
+ *
+ * @return a pseudorandom {@code double} value between zero
+ * (inclusive) and one (exclusive)
+ */
+ default double nextDouble() {
+ return (nextLong() >>> 11) * 0x1.0p-53;
+ }
+
+ /**
+ * Returns a pseudorandomly chosen {@code double} value between zero
+ * (inclusive) and the specified bound (exclusive).
+ *
+ * @implNote The default implementation simply calls
+ * {@code RngSupport.checkBound(bound)} and then
+ * {@code RngSupport.boundedNextDouble(this, bound)}.
+ *
+ * @param bound the upper bound (exclusive) for the returned value.
+ * Must be positive and finite
+ * @return a pseudorandomly chosen {@code double} value between
+ * zero (inclusive) and the bound (exclusive)
+ * @throws IllegalArgumentException if {@code bound} is not
+ * positive and finite
+ */
+ default double nextDouble(double bound) {
+ RngSupport.checkBound(bound);
+ return RngSupport.boundedNextDouble(this, bound);
+ }
+
+ /**
+ * Returns a pseudorandomly chosen {@code double} value between the
+ * specified origin (inclusive) and the specified bound (exclusive).
+ *
+ * @implNote The default implementation simply calls
+ * {@code RngSupport.checkRange(origin, bound)} and then
+ * {@code RngSupport.boundedNextDouble(this, origin, bound)}.
+ *
+ * @param origin the least value that can be returned
+ * @param bound the upper bound (exclusive) for the returned value
+ * @return a pseudorandomly chosen {@code double} value between the
+ * origin (inclusive) and the bound (exclusive)
+ * @throws IllegalArgumentException unless {@code origin} is finite,
+ * {@code bound} is finite, and {@code origin} is less than
+ * {@code bound}
+ */
+ default double nextDouble(double origin, double bound) {
+ RngSupport.checkRange(origin, bound);
+ return RngSupport.boundedNextDouble(this, origin, bound);
+ }
+
+ /**
+ * Returns a pseudorandomly chosen {@code int} value.
+ *
+ * The default implementation uses the 32 high-order bits
+ * from a call to {@code nextLong()}.
+ *
+ * @return a pseudorandomly chosen {@code int} value
+ */
+ default public int nextInt() {
+ return (int)(nextLong() >>> 32);
+ }
+
+ /**
+ * Returns a pseudorandomly chosen {@code int} value between
+ * zero (inclusive) and the specified bound (exclusive).
+ *
+ * @implNote The default implementation simply calls
+ * {@code RngSupport.checkBound(bound)} and then
+ * {@code RngSupport.boundedNextInt(this, bound)}.
+ *
+ * @param bound the upper bound (exclusive) for the returned value. Must be positive.
+ * @return a pseudorandomly chosen {@code int} value between
+ * zero (inclusive) and the bound (exclusive)
+ * @throws IllegalArgumentException if {@code bound} is not positive
+ */
+ default int nextInt(int bound) {
+ RngSupport.checkBound(bound);
+ return RngSupport.boundedNextInt(this, bound);
+ }
+
+ /**
+ * Returns a pseudorandomly chosen {@code int} value between the
+ * specified origin (inclusive) and the specified bound (exclusive).
+ *
+ * @implNote The default implementation simply calls
+ * {@code RngSupport.checkRange(origin, bound)} and then
+ * {@code RngSupport.boundedNextInt(this, origin, bound)}.
+ *
+ * @param origin the least value that can be returned
+ * @param bound the upper bound (exclusive) for the returned value
+ * @return a pseudorandomly chosen {@code int} value between the
+ * origin (inclusive) and the bound (exclusive)
+ * @throws IllegalArgumentException if {@code origin} is greater than
+ * or equal to {@code bound}
+ */
+ default int nextInt(int origin, int bound) {
+ RngSupport.checkRange(origin, bound);
+ return RngSupport.boundedNextInt(this, origin, bound);
+ }
+
+ /**
+ * Returns a pseudorandomly chosen {@code long} value.
+ *
+ * @return a pseudorandomly chosen {@code long} value
+ */
+ long nextLong();
+
+ /**
+ * Returns a pseudorandomly chosen {@code long} value between
+ * zero (inclusive) and the specified bound (exclusive).
+ *
+ * @implNote The default implementation simply calls
+ * {@code RngSupport.checkBound(bound)} and then
+ * {@code RngSupport.boundedNextLong(this, bound)}.
+ *
+ * @param bound the upper bound (exclusive) for the returned value. Must be positive.
+ * @return a pseudorandomly chosen {@code long} value between
+ * zero (inclusive) and the bound (exclusive)
+ * @throws IllegalArgumentException if {@code bound} is not positive
+ */
+ default long nextLong(long bound) {
+ RngSupport.checkBound(bound);
+ return RngSupport.boundedNextLong(this, bound);
+ }
+
+ /**
+ * Returns a pseudorandomly chosen {@code long} value between the
+ * specified origin (inclusive) and the specified bound (exclusive).
+ *
+ * @implNote The default implementation simply calls
+ * {@code RngSupport.checkRange(origin, bound)} and then
+ * {@code RngSupport.boundedNextInt(this, origin, bound)}.
+ *
+ * @param origin the least value that can be returned
+ * @param bound the upper bound (exclusive) for the returned value
+ * @return a pseudorandomly chosen {@code long} value between the
+ * origin (inclusive) and the bound (exclusive)
+ * @throws IllegalArgumentException if {@code origin} is greater than
+ * or equal to {@code bound}
+ */
+ default long nextLong(long origin, long bound) {
+ RngSupport.checkRange(origin, bound);
+ return RngSupport.boundedNextLong(this, origin, bound);
+ }
+
+ /**
+ * Returns a {@code double} value pseudorandomly chosen from
+ * a Gaussian (normal) distribution whose mean is 0 and whose
+ * standard deviation is 1.
+ *
+ * @return a {@code double} value pseudorandomly chosen from a
+ * Gaussian distribution
+ */
+ default double nextGaussian() {
+ return RngSupport.computeNextGaussian(this);
+ }
+
+ /**
+ * Returns a {@code double} value pseudorandomly chosen from
+ * a Gaussian (normal) distribution with a mean and
+ * standard deviation specified by the arguments.
+ *
+ * @param mean the mean of the Gaussian distribution to be drawn from
+ * @param stddev the standard deviation of the Gaussian distribution to be drawn from
+ * @return a {@code double} value pseudorandomly chosen from the
+ * specified Gaussian distribution
+ */
+ default double nextGaussian(double mean, double stddev) {
+ return mean + RngSupport.computeNextGaussian(this) * stddev * stddev;
+ }
+
+ /**
+ * Returns a nonnegative {@code double} value pseudorandomly chosen
+ * from an exponential distribution whose mean is 1.
+ *
+ * @return a nonnegative {@code double} value pseudorandomly chosen from an
+ * exponential distribution
+ */
+ default double nextExponential() {
+ return RngSupport.computeNextExponential(this);
+ }
+
+
+ /**
+ * Returns the period of this {@code Rng} object.
+ *
+ * @return a {@code BigInteger} whose value is the number of
+ * distinct possible states of this {@code Rng} object,
+ * or 0 if unknown, or negative if extremely large.
+ */
+ BigInteger period();
+
+ /**
+ * The value (0) returned by the {@code period()} method if the period is unknown.
+ */
+ static final BigInteger UNKNOWN_PERIOD = BigInteger.ZERO;
+
+ /**
+ * The (negative) value returned by the {@code period()} method if this generator
+ * has no period because it is truly random rather than just pseudorandom.
+ */
+ static final BigInteger TRULY_RANDOM = BigInteger.valueOf(-1);
+
+ /**
+ * The (negative) value that may be returned by the {@code period()} method
+ * if this generator has a huge period (larger than 2**(2**16)).
+ */
+ static final BigInteger HUGE_PERIOD = BigInteger.valueOf(-2);
+}
diff -r c646b256fbcc -r 6d87e9f7a1ec newrandom/RngSupport.java
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/newrandom/RngSupport.java Thu May 23 16:45:56 2019 -0400
@@ -0,0 +1,1018 @@
+/*
+ * Copyright (c) 2013, 2016, 2019, Oracle and/or its affiliates. All rights reserved.
+ * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ */
+
+// package java.util;
+
+import java.util.Spliterator;
+import java.util.function.Consumer;
+import java.util.function.IntConsumer;
+import java.util.function.LongConsumer;
+import java.util.function.DoubleConsumer;
+import java.util.stream.StreamSupport;
+import java.util.stream.IntStream;
+import java.util.stream.LongStream;
+import java.util.stream.DoubleStream;
+// import java.util.DoubleZigguratTables;
+
+/**
+ * Low-level utility methods helpful for implementing pseudorandom number generators.
+ *
+ * This class is mostly for library writers creating specific implementations of the interface {@link java.util.Rng}.
+ *
+ * @author Guy Steele
+ * @author Doug Lea
+ * @since 1.9
+ */
+public class RngSupport {
+
+ /*
+ * Implementation Overview.
+ *
+ * This class provides utility methods and constants frequently
+ * useful in the implentation of pseudorandom number generators
+ * that satisfy the interface {@code java.util.Rng}.
+ *
+ * File organization: First some message strings, then the main
+ * public methods, followed by a non-public base spliterator class.
+ */
+
+ // IllegalArgumentException messages
+ static final String BadSize = "size must be non-negative";
+ static final String BadDistance = "jump distance must be finite, positive, and an exact integer";
+ static final String BadBound = "bound must be positive";
+ static final String BadFloatingBound = "bound must be finite and positive";
+ static final String BadRange = "bound must be greater than origin";
+
+ /* ---------------- public methods ---------------- */
+
+ /**
+ * Check a {@code long} proposed stream size for validity.
+ *
+ * @param streamSize the proposed stream size
+ * @throws IllegalArgumentException if {@code streamSize} is negative
+ */
+ public static void checkStreamSize(long streamSize) {
+ if (streamSize < 0L)
+ throw new IllegalArgumentException(BadSize);
+ }
+
+ /**
+ * Check a {@code double} proposed jump distance for validity.
+ *
+ * @param distance the proposed jump distance
+ * @throws IllegalArgumentException if {@code size} not positive,
+ * finite, and an exact integer
+ */
+ public static void checkJumpDistance(double distance) {
+ if (!(distance > 0.0 && distance < Float.POSITIVE_INFINITY && distance == Math.floor(distance)))
+ throw new IllegalArgumentException(BadDistance);
+ }
+
+ /**
+ * Checks a {@code float} upper bound value for validity.
+ *
+ * @param bound the upper bound (exclusive)
+ * @throws IllegalArgumentException if {@code bound} is not
+ * positive and finite
+ */
+ public static void checkBound(float bound) {
+ if (!(bound > 0.0 && bound < Float.POSITIVE_INFINITY))
+ throw new IllegalArgumentException(BadFloatingBound);
+ }
+
+ /**
+ * Checks a {@code double} upper bound value for validity.
+ *
+ * @param bound the upper bound (exclusive)
+ * @throws IllegalArgumentException if {@code bound} is not
+ * positive and finite
+ */
+ public static void checkBound(double bound) {
+ if (!(bound > 0.0 && bound < Double.POSITIVE_INFINITY))
+ throw new IllegalArgumentException(BadFloatingBound);
+ }
+
+ /**
+ * Checks an {@code int} upper bound value for validity.
+ *
+ * @param bound the upper bound (exclusive)
+ * @throws IllegalArgumentException if {@code bound} is not positive
+ */
+ public static void checkBound(int bound) {
+ if (bound <= 0)
+ throw new IllegalArgumentException(BadBound);
+ }
+
+ /**
+ * Checks a {@code long} upper bound value for validity.
+ *
+ * @param bound the upper bound (exclusive)
+ * @throws IllegalArgumentException if {@code bound} is not positive
+ */
+ public static void checkBound(long bound) {
+ if (bound <= 0)
+ throw new IllegalArgumentException(BadBound);
+ }
+
+ /**
+ * Checks a {@code float} range for validity.
+ *
+ * @param origin the least value (inclusive) in the range
+ * @param bound the upper bound (exclusive) of the range
+ * @throws IllegalArgumentException unless {@code origin} is finite,
+ * {@code bound} is finite, and {@code bound - origin} is finite
+ */
+ public static void checkRange(float origin, float bound) {
+ if (!(origin < bound && (bound - origin) < Float.POSITIVE_INFINITY))
+ throw new IllegalArgumentException(BadRange);
+ }
+
+ /**
+ * Checks a {@code double} range for validity.
+ *
+ * @param origin the least value (inclusive) in the range
+ * @param bound the upper bound (exclusive) of the range
+ * @throws IllegalArgumentException unless {@code origin} is finite,
+ * {@code bound} is finite, and {@code bound - origin} is finite
+ */
+ public static void checkRange(double origin, double bound) {
+ if (!(origin < bound && (bound - origin) < Double.POSITIVE_INFINITY))
+ throw new IllegalArgumentException(BadRange);
+ }
+
+ /**
+ * Checks an {@code int} range for validity.
+ *
+ * @param origin the least value that can be returned
+ * @param bound the upper bound (exclusive) for the returned value
+ * @throws IllegalArgumentException if {@code origin} is greater than
+ * or equal to {@code bound}
+ */
+ public static void checkRange(int origin, int bound) {
+ if (origin >= bound)
+ throw new IllegalArgumentException(BadRange);
+ }
+
+ /**
+ * Checks a {@code long} range for validity.
+ *
+ * @param origin the least value that can be returned
+ * @param bound the upper bound (exclusive) for the returned value
+ * @throws IllegalArgumentException if {@code origin} is greater than
+ * or equal to {@code bound}
+ */
+ public static void checkRange(long origin, long bound) {
+ if (origin >= bound)
+ throw new IllegalArgumentException(BadRange);
+ }
+
+ public static long[] convertSeedBytesToLongs(byte[] seed, int n, int z) {
+ final long[] result = new long[n];
+ final int m = Math.min(seed.length, n << 3);
+ // Distribute seed bytes into the words to be formed.
+ for (int j = 0; j < m; j++) {
+ result[j>>3] = (result[j>>3] << 8) | seed[j];
+ }
+ // If there aren't enough seed bytes for all the words we need,
+ // use a SplitMix-style PRNG to fill in the rest.
+ long v = result[0];
+ for (int j = (m + 7) >> 3; j < n; j++) {
+ result[j] = mixMurmur64(v += SILVER_RATIO_64);
+ }
+ // Finally, we need to make sure the last z words are not all zero.
+ search: {
+ for (int j = n - z; j < n; j++) {
+ if (result[j] != 0) break search;
+ }
+ // If they are, fill in using a SplitMix-style PRNG.
+ // Using "& ~1L" in the next line defends against the case z==1
+ // by guaranteeing that the first generated value will be nonzero.
+ long w = result[0] & ~1L;
+ for (int j = n - z; j < n; j++) {
+ result[j] = mixMurmur64(w += SILVER_RATIO_64);
+ }
+ }
+ return result;
+ }
+
+ public static int[] convertSeedBytesToInts(byte[] seed, int n, int z) {
+ final int[] result = new int[n];
+ final int m = Math.min(seed.length, n << 2);
+ // Distribute seed bytes into the words to be formed.
+ for (int j = 0; j < m; j++) {
+ result[j>>2] = (result[j>>2] << 8) | seed[j];
+ }
+ // If there aren't enough seed bytes for all the words we need,
+ // use a SplitMix-style PRNG to fill in the rest.
+ int v = result[0];
+ for (int j = (m + 3) >> 2; j < n; j++) {
+ result[j] = mixMurmur32(v += SILVER_RATIO_32);
+ }
+ // Finally, we need to make sure the last z words are not all zero.
+ search: {
+ for (int j = n - z; j < n; j++) {
+ if (result[j] != 0) break search;
+ }
+ // If they are, fill in using a SplitMix-style PRNG.
+ // Using "& ~1" in the next line defends against the case z==1
+ // by guaranteeing that the first generated value will be nonzero.
+ int w = result[0] & ~1;
+ for (int j = n - z; j < n; j++) {
+ result[j] = mixMurmur32(w += SILVER_RATIO_32);
+ }
+ }
+ return result;
+ }
+
+ /*
+ * Bounded versions of nextX methods used by streams, as well as
+ * the public nextX(origin, bound) methods. These exist mainly to
+ * avoid the need for multiple versions of stream spliterators
+ * across the different exported forms of streams.
+ */
+
+ /**
+ * This is the form of {@code nextLong} used by a {@code LongStream}
+ * {@code Spliterator} and by the public method
+ * {@code nextLong(origin, bound)}. If {@code origin} is greater
+ * than {@code bound}, then this method simply calls the unbounded
+ * version of {@code nextLong()}, choosing pseudorandomly from
+ * among all 264 possible {@code long} values}, and
+ * otherwise uses one or more calls to {@code nextLong()} to
+ * choose a value pseudorandomly from the possible values
+ * between {@code origin} (inclusive) and {@code bound} (exclusive).
+ *
+ * @implNote This method first calls {@code nextLong()} to obtain
+ * a {@code long} value that is assumed to be pseudorandomly
+ * chosen uniformly and independently from the 264
+ * possible {@code long} values (that is, each of the 264
+ * possible long values is equally likely to be chosen).
+ * Under some circumstances (when the specified range is not
+ * a power of 2), {@code nextLong()} may be called additional times
+ * to ensure that that the values in the specified range are
+ * equally likely to be chosen (provided the assumption holds).
+ *
+ * The implementation considers four cases:
+ * The implementation considers two cases:
+ * Instances of {@code SplittableRandom} are not cryptographically
+ * secure. Consider instead using {@link java.security.SecureRandom}
+ * in security-sensitive applications. Additionally,
+ * default-constructed instances do not use a cryptographically random
+ * seed unless the {@linkplain System#getProperty system property}
+ * {@code java.util.secureRandomSeed} is set to {@code true}.
+ *
+ * @author Guy Steele
+ * @author Doug Lea
+ * @since 1.8
+ */
+public final class SplittableRandom extends AbstractSplittableRng {
+
+ /*
+ * Implementation Overview.
+ *
+ * This algorithm was inspired by the "DotMix" algorithm by
+ * Leiserson, Schardl, and Sukha "Deterministic Parallel
+ * Random-Number Generation for Dynamic-Multithreading Platforms",
+ * PPoPP 2012, as well as those in "Parallel random numbers: as
+ * easy as 1, 2, 3" by Salmon, Morae, Dror, and Shaw, SC 2011. It
+ * differs mainly in simplifying and cheapening operations.
+ *
+ * The primary update step (method nextSeed()) is to add a
+ * constant ("gamma") to the current (64 bit) seed, forming a
+ * simple sequence. The seed and the gamma values for any two
+ * SplittableRandom instances are highly likely to be different.
+ *
+ * Methods nextLong, nextInt, and derivatives do not return the
+ * sequence (seed) values, but instead a hash-like bit-mix of
+ * their bits, producing more independently distributed sequences.
+ * For nextLong, the mix64 function is based on David Stafford's
+ * (http://zimbry.blogspot.com/2011/09/better-bit-mixing-improving-on.html)
+ * "Mix13" variant of the "64-bit finalizer" function in Austin
+ * Appleby's MurmurHash3 algorithm (see
+ * http://code.google.com/p/smhasher/wiki/MurmurHash3). The mix32
+ * function is based on Stafford's Mix04 mix function, but returns
+ * the upper 32 bits cast as int.
+ *
+ * The split operation uses the current generator to form the seed
+ * and gamma for another SplittableRandom. To conservatively
+ * avoid potential correlations between seed and value generation,
+ * gamma selection (method mixGamma) uses different
+ * (Murmurhash3's) mix constants. To avoid potential weaknesses
+ * in bit-mixing transformations, we restrict gammas to odd values
+ * with at least 24 0-1 or 1-0 bit transitions. Rather than
+ * rejecting candidates with too few or too many bits set, method
+ * mixGamma flips some bits (which has the effect of mapping at
+ * most 4 to any given gamma value). This reduces the effective
+ * set of 64bit odd gamma values by about 2%, and serves as an
+ * automated screening for sequence constant selection that is
+ * left as an empirical decision in some other hashing and crypto
+ * algorithms.
+ *
+ * The resulting generator thus transforms a sequence in which
+ * (typically) many bits change on each step, with an inexpensive
+ * mixer with good (but less than cryptographically secure)
+ * avalanching.
+ *
+ * The default (no-argument) constructor, in essence, invokes
+ * split() for a common "defaultGen" SplittableRandom. Unlike
+ * other cases, this split must be performed in a thread-safe
+ * manner, so we use an AtomicLong to represent the seed rather
+ * than use an explicit SplittableRandom. To bootstrap the
+ * defaultGen, we start off using a seed based on current time
+ * unless the java.util.secureRandomSeed property is set. This
+ * serves as a slimmed-down (and insecure) variant of SecureRandom
+ * that also avoids stalls that may occur when using /dev/random.
+ *
+ * It is a relatively simple matter to apply the basic design here
+ * to use 128 bit seeds. However, emulating 128bit arithmetic and
+ * carrying around twice the state add more overhead than appears
+ * warranted for current usages.
+ *
+ * File organization: First the non-public methods that constitute
+ * the main algorithm, then the main public methods, followed by
+ * some custom spliterator classes needed for stream methods.
+ */
+
+ /**
+ * The golden ratio scaled to 64bits, used as the initial gamma
+ * value for (unsplit) SplittableRandoms.
+ */
+ private static final long GOLDEN_GAMMA = 0x9e3779b97f4a7c15L;
+
+ /**
+ * The seed. Updated only via method nextSeed.
+ */
+ private long seed;
+
+ /**
+ * The step value.
+ */
+ private final long gamma;
+
+ /**
+ * Internal constructor used by all others except default constructor.
+ */
+ private SplittableRandom(long seed, long gamma) {
+ this.seed = seed;
+ this.gamma = gamma;
+ }
+
+ /* The implementation of AbstractSplittableRng requires this. */
+ // SplittableRandom getThis() { return this; }
+
+ /**
+ * Computes Stafford variant 13 of 64bit mix function.
+ * http://zimbry.blogspot.com/2011/09/better-bit-mixing-improving-on.html
+ */
+ private static long mix64(long z) {
+ z = (z ^ (z >>> 30)) * 0xbf58476d1ce4e5b9L;
+ z = (z ^ (z >>> 27)) * 0x94d049bb133111ebL;
+ return z ^ (z >>> 31);
+ }
+
+ /**
+ * Returns the 32 high bits of Stafford variant 4 mix64 function as int.
+ * http://zimbry.blogspot.com/2011/09/better-bit-mixing-improving-on.html
+ */
+ private static int mix32(long z) {
+ z = (z ^ (z >>> 33)) * 0x62a9d9ed799705f5L;
+ return (int)(((z ^ (z >>> 28)) * 0xcb24d0a5c88c35b3L) >>> 32);
+ }
+
+ /**
+ * Returns the gamma value to use for a new split instance.
+ * Uses the 64bit mix function from MurmurHash3.
+ * https://github.com/aappleby/smhasher/wiki/MurmurHash3
+ */
+ private static long mixGamma(long z) {
+ z = (z ^ (z >>> 33)) * 0xff51afd7ed558ccdL; // MurmurHash3 mix constants
+ z = (z ^ (z >>> 33)) * 0xc4ceb9fe1a85ec53L;
+ z = (z ^ (z >>> 33)) | 1L; // force to be odd
+ int n = Long.bitCount(z ^ (z >>> 1)); // ensure enough transitions
+ return (n < 24) ? z ^ 0xaaaaaaaaaaaaaaaaL : z;
+ }
+
+ /**
+ * Adds gamma to seed.
+ */
+ private long nextSeed() {
+ return seed += gamma;
+ }
+
+ /**
+ * The seed generator for default constructors.
+ */
+ private static final AtomicLong defaultGen = new AtomicLong(RngSupport.initialSeed());
+
+ /* ---------------- public methods ---------------- */
+
+ /**
+ * Creates a new SplittableRandom instance using the specified
+ * initial seed. SplittableRandom instances created with the same
+ * seed in the same program generate identical sequences of values.
+ *
+ * @param seed the initial seed
+ */
+ public SplittableRandom(long seed) {
+ this(seed, GOLDEN_GAMMA);
+ }
+
+ /**
+ * Creates a new SplittableRandom instance that is likely to
+ * generate sequences of values that are statistically independent
+ * of those of any other instances in the current program; and
+ * may, and typically does, vary across program invocations.
+ */
+ public SplittableRandom() { // emulate defaultGen.split()
+ long s = defaultGen.getAndAdd(2 * GOLDEN_GAMMA);
+ this.seed = mix64(s);
+ this.gamma = mixGamma(s + GOLDEN_GAMMA);
+ }
+
+ // public SplittableRandom copy() { return new SplittableRandom(seed, gamma); }
+
+ /**
+ * Constructs and returns a new SplittableRandom instance that
+ * shares no mutable state with this instance. However, with very
+ * high probability, the set of values collectively generated by
+ * the two objects has the same statistical properties as if the
+ * same quantity of values were generated by a single thread using
+ * a single SplittableRandom object. Either or both of the two
+ * objects may be further split using the {@code split()} method,
+ * and the same expected statistical properties apply to the
+ * entire set of generators constructed by such recursive
+ * splitting.
+ *
+ * @return the new SplittableRandom instance
+ */
+ public SplittableRandom split() {
+ return new SplittableRandom(nextLong(), mixGamma(nextSeed()));
+ }
+
+ public SplittableRandom split(SplittableRng source) {
+ return new SplittableRandom(source.nextLong(), mixGamma(source.nextLong()));
+ }
+
+ /**
+ * Returns a pseudorandom {@code int} value.
+ *
+ * @return a pseudorandom {@code int} value
+ */
+ public int nextInt() {
+ return mix32(nextSeed());
+ }
+
+ /**
+ * Returns a pseudorandom {@code long} value.
+ *
+ * @return a pseudorandom {@code long} value
+ */
+ public long nextLong() {
+ return mix64(nextSeed());
+ }
+
+ static final BigInteger thePeriod = BigInteger.ONE.shiftLeft(64); // Period is 2**64
+ public BigInteger period() { return thePeriod; }
+
+}
diff -r c646b256fbcc -r 6d87e9f7a1ec newrandom/SplittableRng.java
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/newrandom/SplittableRng.java Thu May 23 16:45:56 2019 -0400
@@ -0,0 +1,192 @@
+/*
+ * Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
+ * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ */
+// package java.util;
+
+import java.util.stream.Stream;
+import java.util.stream.StreamSupport;
+import java.util.stream.IntStream;
+import java.util.stream.LongStream;
+import java.util.stream.DoubleStream;
+
+/**
+ * This interface is designed to provide a common protocol for objects
+ * that generate sequences of pseudorandom numbers (or Boolean values)
+ * and furthermore can be Ideally, all {@code SplittableRNG} objects produced by recursive
+ * splitting from a single original {@code SplittableRNG} object are
+ * statistically independent of one another and individually uniform.
+ * Therefore we would expect the set of values collectively generated
+ * by a set of such objects to have the same statistical properties as
+ * if the same quantity of values were generated by a single thread
+ * using a single {@code SplittableRNG} object. In practice, one must
+ * settle for some approximation to independence and uniformity.
+ *
+ * Methods are provided to perform a single splitting operation and
+ * also to produce a stream of generators split off from the original
+ * (by either iterative or recursive splitting, or a combination).
+ *
+ * An implementation of the {@code SplittableRng} interface must provide
+ * concrete definitions for the methods {@code nextInt()}, {@code nextLong},
+ * {@code period()}, {@code split()}, {@code split(SplittableRng)},
+ * {@code splits()}, {@code splits(long)}, {@code splits(SplittableRng)},
+ * and {@code splits(long, SplittableRng)}. Perhaps the most convenient
+ * way to implement this interface is to extend the abstract class
+ * {@link java.util.AbstractSplittableRng}.
+ *
+ * Objects that implement {@code java.util.SplittableRNG} are
+ * typically not cryptographically secure. Consider instead using
+ * {@link java.security.SecureRandom} to get a cryptographically
+ * secure pseudo-random number generator for use by
+ * security-sensitive applications.
+ *
+ * @author Guy Steele
+ * @since 1.9
+ */
+interface SplittableRng extends StreamableRng {
+
+ /**
+ * Returns a new pseudorandom number generator, split off from
+ * this one, that implements the {@code Rng} and {@code SplittableRng}
+ * interfaces.
+ *
+ * This pseudorandom number generator may be used as a source of
+ * pseudorandom bits used to initialize the state the new one.
+ *
+ * @return a new object that implements the {@code Rng} and
+ * {@code SplittableRng} interfaces
+ */
+ SplittableRng split();
+
+ /**
+ * Returns a new pseudorandom number generator, split off from
+ * this one, that implements the {@code Rng} and {@code SplittableRng}
+ * interfaces.
+ *
+ * @param source a {@code SplittableRng} instance to be used instead
+ * of this one as a source of pseudorandom bits used to
+ * initialize the state of the new ones.
+ *
+ * @return an object that implements the {@code Rng} and
+ * {@code SplittableRng} interfaces
+ */
+ SplittableRng split(SplittableRng source);
+
+ /**
+ * Returns an effectively unlimited stream of new pseudorandom
+ * number generators, each of which implements the {@code SplittableRng}
+ * interface.
+ *
+ * This pseudorandom number generator may be used as a source of
+ * pseudorandom bits used to initialize the state the new ones.
+ *
+ * @implNote It is permitted to implement this method in a manner
+ * equivalent to {@code splits(Long.MAX_VALUE)}.
+ *
+ * @return a stream of {@code SplittableRng} objects
+ */
+ default Stream An implementation of the {@code StreamableRng} interface must provide
+ * concrete definitions for the methods {@code nextInt()}, {@code nextLong},
+ * {@code period()}, and {@code rngs()}.
+ * Default implementations are provided for all other methods.
+ *
+ * Objects that implement {@code java.util.StreamableRng} are typically
+ * not cryptographically secure. Consider instead using
+ * {@link java.security.SecureRandom} to get a cryptographically
+ * secure pseudo-random number generator for use by
+ * security-sensitive applications.
+ *
+ * @author Guy Steele
+ * @since 1.9
+ */
+
+import java.util.stream.Stream;
+
+interface StreamableRng extends Rng {
+ /**
+ * Returns an effectively unlimited stream of objects, each of
+ * which implements the {@code Rng} interface. Ideally the
+ * generators in the stream will appear to be statistically
+ * independent. The new generators should be of the same kind
+ * as this generator.
+ *
+ * @implNote It is permitted to implement this method in a manner
+ * equivalent to {@code rngs(Long.MAX_VALUE)}.
+ *
+ * @return a stream of objects that implement the {@code Rng} interface
+ */
+ Stream Usages of this class should typically be of the form:
+ * {@code ThreadLocalRandom.current().nextX(...)} (where
+ * {@code X} is {@code Int}, {@code Long}, etc).
+ * When all usages are of this form, it is never possible to
+ * accidently share a {@code ThreadLocalRandom} across multiple threads.
+ *
+ * This class also provides additional commonly used bounded random
+ * generation methods.
+ *
+ * Instances of {@code ThreadLocalRandom} are not cryptographically
+ * secure. Consider instead using {@link java.security.SecureRandom}
+ * in security-sensitive applications. Additionally,
+ * default-constructed instances do not use a cryptographically random
+ * seed unless the {@linkplain System#getProperty system property}
+ * {@code java.util.secureRandomSeed} is set to {@code true}.
+ *
+ * @since 1.7
+ * @author Doug Lea
+ */
+public class ThreadLocalRandom extends Random {
+ /*
+ * This class implements the java.util.Random API (and subclasses
+ * Random) using a single static instance that accesses random
+ * number state held in class Thread (primarily, field
+ * threadLocalRandomSeed). In doing so, it also provides a home
+ * for managing package-private utilities that rely on exactly the
+ * same state as needed to maintain the ThreadLocalRandom
+ * instances. We leverage the need for an initialization flag
+ * field to also use it as a "probe" -- a self-adjusting thread
+ * hash used for contention avoidance, as well as a secondary
+ * simpler (xorShift) random seed that is conservatively used to
+ * avoid otherwise surprising users by hijacking the
+ * ThreadLocalRandom sequence. The dual use is a marriage of
+ * convenience, but is a simple and efficient way of reducing
+ * application-level overhead and footprint of most concurrent
+ * programs.
+ *
+ * Even though this class subclasses java.util.Random, it uses the
+ * same basic algorithm as java.util.SplittableRandom. (See its
+ * internal documentation for explanations, which are not repeated
+ * here.) Because ThreadLocalRandoms are not splittable
+ * though, we use only a single 64bit gamma.
+ *
+ * Because this class is in a different package than class Thread,
+ * field access methods use Unsafe to bypass access control rules.
+ * To conform to the requirements of the Random superclass
+ * constructor, the common static ThreadLocalRandom maintains an
+ * "initialized" field for the sake of rejecting user calls to
+ * setSeed while still allowing a call from constructor. Note
+ * that serialization is completely unnecessary because there is
+ * only a static singleton. But we generate a serial form
+ * containing "rnd" and "initialized" fields to ensure
+ * compatibility across versions.
+ *
+ * Implementations of non-core methods are mostly the same as in
+ * SplittableRandom, that were in part derived from a previous
+ * version of this class.
+ *
+ * The nextLocalGaussian ThreadLocal supports the very rarely used
+ * nextGaussian method by providing a holder for the second of a
+ * pair of them. As is true for the base class version of this
+ * method, this time/space tradeoff is probably never worthwhile,
+ * but we provide identical statistical properties.
+ */
+
+ /** Generates per-thread initialization/probe field */
+ private static final AtomicInteger probeGenerator =
+ new AtomicInteger();
+
+ /**
+ * The next seed for default constructors.
+ */
+ private static final AtomicLong seeder = new AtomicLong(RngSupport.initialSeed());
+
+ /**
+ * The seed increment
+ */
+ private static final long GAMMA = 0x9e3779b97f4a7c15L;
+
+ /**
+ * The increment for generating probe values
+ */
+ private static final int PROBE_INCREMENT = 0x9e3779b9;
+
+ /**
+ * The increment of seeder per new instance
+ */
+ private static final long SEEDER_INCREMENT = 0xbb67ae8584caa73bL;
+
+ // Constants from SplittableRandom
+ private static final double DOUBLE_UNIT = 0x1.0p-53; // 1.0 / (1L << 53)
+ private static final float FLOAT_UNIT = 0x1.0p-24f; // 1.0f / (1 << 24)
+
+ /** Rarely-used holder for the second of a pair of Gaussians */
+ private static final ThreadLocal Series of generated values pass the TestU01 BigCrush and PractRand test suites
+ * that measure independence and uniformity properties of random number generators,
+ * except that it does not pass the binary rank tests of PractRand,
+ * which fail due to the lowest bit being an LFSR; all other bits pass all tests.
+ * For this reason may be best for some purposes to use this generator to generate
+ * pseudorandom {@code int}, {@code float}, and {@code double} values but not
+ * {@code long} values. For the same reason, it may be best not to use the
+ * method {@code nextGaussian} or {@code nextExponential} with this generator.
+ *
+ * The class {@code Xoroshiro128Plus} uses the {@code xoroshiro128} algorithm,
+ * version 1.0 (parameters 24, 16, 37), with the "+" scrambler
+ * (the returned value is the sum of the two state variables {@code x0} and {@code x1}).
+ * Its state consists of two {@code long} fields {@code x0} and {@code x1},
+ * which can take on any values provided that they are not both zero.
+ * The period of this generator is 2128-1.
+ *
+ * The 64-bit values produced by the {@code nextLong()} method are equidistributed.
+ * To be precise, over the course of the cycle of length 2128-1,
+ * each nonzero {@code long} value is generated 264 times,
+ * but the value 0 is generated only 264-1 times.
+ * The values produced by the {@code nextInt()}, {@code nextFloat()}, and {@code nextDouble()}
+ * methods are likewise equidistributed.
+ *
+ * Instances {@code Xoroshiro128Plus} are not thread-safe.
+ * They are designed to be used so that each thread as its own instance.
+ * The methods {@link #jump} and {@link #leap} and {@link #jumps} and {@link #leaps}
+ * can be used to construct new instances of {@code Xoroshiro128Plus} that traverse
+ * other parts of the state cycle.
+ *
+ * Instances of {@code Xoroshiro128Plus} are not cryptographically
+ * secure. Consider instead using {@link java.security.SecureRandom}
+ * in security-sensitive applications. Additionally,
+ * default-constructed instances do not use a cryptographically random
+ * seed unless the {@linkplain System#getProperty system property}
+ * {@code java.util.secureRandomSeed} is set to {@code true}.
+ *
+ * @author Guy Steele
+ * @author Doug Lea
+ * @since 1.8
+ */
+public final class Xoroshiro128Plus implements LeapableRng {
+
+ /*
+ * Implementation Overview.
+ *
+ * This is an implementation of the xoroshiro128+ algorithm written
+ * in 2016 by David Blackman and Sebastiano Vigna (vigna@acm.org),
+ * and updated with improved parameters in 2018.
+ * See http://xoshiro.di.unimi.it and these two papers:
+ *
+ * Sebastiano Vigna. 2016. An Experimental Exploration of Marsaglia's
+ * xorshift Generators, Scrambled. ACM Transactions on Mathematical
+ * Software 42, 4, Article 30 (June 2016), 23 pages.
+ * https://doi.org/10.1145/2845077
+ *
+ * David Blackman and Sebastiano Vigna. 2018. Scrambled Linear
+ * Pseudorandom Number Generators. Computing Research Repository (CoRR).
+ * http://arxiv.org/abs/1805.01407
+ *
+ * The jump operation moves the current generator forward by 2*64
+ * steps; this has the same effect as calling nextLong() 2**64
+ * times, but is much faster. Similarly, the leap operation moves
+ * the current generator forward by 2*96 steps; this has the same
+ * effect as calling nextLong() 2**96 times, but is much faster.
+ * The copy method may be used to make a copy of the current
+ * generator. Thus one may repeatedly and cumulatively copy and
+ * jump to produce a sequence of generators whose states are well
+ * spaced apart along the overall state cycle (indeed, the jumps()
+ * and leaps() methods each produce a stream of such generators).
+ * The generators can then be parceled out to other threads.
+ *
+ * File organization: First the non-public methods that constitute the
+ * main algorithm, then the public methods. Note that many methods are
+ * defined by classes {@code AbstractJumpableRng} and {@code AbstractRng}.
+ */
+
+ /* ---------------- static fields ---------------- */
+
+ /**
+ * The seed generator for default constructors.
+ */
+ private static final AtomicLong defaultGen = new AtomicLong(RngSupport.initialSeed());
+
+ /*
+ * The period of this generator, which is 2**128 - 1.
+ */
+ private static final BigInteger thePeriod =
+ BigInteger.ONE.shiftLeft(128).subtract(BigInteger.ONE);
+
+ /* ---------------- instance fields ---------------- */
+
+ /**
+ * The per-instance state.
+ * At least one of the two fields x0 and x1 must be nonzero.
+ */
+ private long x0, x1;
+
+ /* ---------------- constructors ---------------- */
+
+ /**
+ * Basic constructor that initializes all fields from parameters.
+ * It then adjusts the field values if necessary to ensure that
+ * all constraints on the values of fields are met.
+ */
+ public Xoroshiro128Plus(long x0, long x1) {
+ this.x0 = x0;
+ this.x1 = x1;
+ // If x0 and x1 are both zero, we must choose nonzero values.
+ if ((x0 | x1) == 0) {
+ // At least one of the two values generated here will be nonzero.
+ this.x0 = RngSupport.mixStafford13(x0 += RngSupport.GOLDEN_RATIO_64);
+ this.x1 = (x0 += RngSupport.GOLDEN_RATIO_64);
+ }
+ }
+
+ /**
+ * Creates a new instance of {@code Xoroshiro128Plus} using the
+ * specified {@code long} value as the initial seed. Instances of
+ * {@code Xoroshiro128Plus} created with the same seed in the same
+ * program generate identical sequences of values.
+ *
+ * @param seed the initial seed
+ */
+ public Xoroshiro128Plus(long seed) {
+ // Using a value with irregularly spaced 1-bits to xor the seed
+ // argument tends to improve "pedestrian" seeds such as 0 or
+ // other small integers. We may as well use SILVER_RATIO_64.
+ //
+ // The x values are then filled in as if by a SplitMix PRNG with
+ // GOLDEN_RATIO_64 as the gamma value and Stafford13 as the mixer.
+ this(RngSupport.mixStafford13(seed ^= RngSupport.SILVER_RATIO_64),
+ RngSupport.mixStafford13(seed + RngSupport.GOLDEN_RATIO_64));
+ }
+
+ /**
+ * Creates a new instance of {@code Xoroshiro128Plus} that is likely to
+ * generate sequences of values that are statistically independent
+ * of those of any other instances in the current program execution,
+ * but may, and typically does, vary across program invocations.
+ */
+ public Xoroshiro128Plus() {
+ // Using GOLDEN_RATIO_64 here gives us a good Weyl sequence of values.
+ this(defaultGen.getAndAdd(RngSupport.GOLDEN_RATIO_64));
+ }
+
+ /**
+ * Creates a new instance of {@code Xoroshiro128Plus} using the specified array of
+ * initial seed bytes. Instances of {@code Xoroshiro128Plus} created with the same
+ * seed array in the same program execution generate identical sequences of values.
+ *
+ * @param seed the initial seed
+ */
+ public Xoroshiro128Plus(byte[] seed) {
+ // Convert the seed to 2 long values, which are not both zero.
+ long[] data = RngSupport.convertSeedBytesToLongs(seed, 2, 2);
+ long x0 = data[0], x1 = data[1];
+ this.x0 = x0;
+ this.x1 = x1;
+ }
+
+ /* ---------------- public methods ---------------- */
+
+ public Xoroshiro128Plus copy() { return new Xoroshiro128Plus(x0, x1); }
+
+/*
+
+To the extent possible under law, the author has dedicated all copyright
+and related and neighboring rights to this software to the public domain
+worldwide. This software is distributed without any warranty.
+
+See Series of generated values pass the TestU01 BigCrush and PractRand test suites
+ * that measure independence and uniformity properties of random number generators.
+ *
+ * The class {@code Xoroshiro128StarStar} uses the {@code xoroshiro128} algorithm,
+ * version 1.0 (parameters 24, 16, 37), with the "**" scrambler (a mixing function).
+ * Its state consists of two {@code long} fields {@code x0} and {@code x1},
+ * which can take on any values provided that they are not both zero.
+ * The period of this generator is 2128-1.
+ *
+ * The 64-bit values produced by the {@code nextLong()} method are equidistributed.
+ * To be precise, over the course of the cycle of length 2128-1,
+ * each nonzero {@code long} value is generated 264 times,
+ * but the value 0 is generated only 264-1 times.
+ * The values produced by the {@code nextInt()}, {@code nextFloat()}, and {@code nextDouble()}
+ * methods are likewise equidistributed.
+ *
+ * In fact, the 64-bit values produced by the {@code nextLong()} method are 2-equidistributed.
+ * To be precise: consider the (overlapping) length-2 subsequences of the cycle of 64-bit
+ * values produced by {@code nextLong()} (assuming no other methods are called that would
+ * affect the state). There are 2128-1 such subsequences, and each subsequence,
+ * which consists of 2 64-bit values, can have one of 2128 values. Of those
+ * 2128 subsequence values, each one is generated exactly once over the course
+ * of the entire cycle, except that the subsequence (0, 0) never appears.
+ * The values produced by the {@code nextInt()}, {@code nextFloat()}, and {@code nextDouble()}
+ * methods are likewise 2-equidistributed, but note that that the subsequence (0, 0)
+ * can also appear (but occurring somewhat less frequently than all other subsequences),
+ * because the values produced by those methods have fewer than 64 randomly chosen bits.
+ *
+ * Instances {@code Xoroshiro128StarStar} are not thread-safe.
+ * They are designed to be used so that each thread as its own instance.
+ * The methods {@link #jump} and {@link #leap} and {@link #jumps} and {@link #leaps}
+ * can be used to construct new instances of {@code Xoroshiro128StarStar} that traverse
+ * other parts of the state cycle.
+ *
+ * Instances of {@code Xoroshiro128StarStar} are not cryptographically
+ * secure. Consider instead using {@link java.security.SecureRandom}
+ * in security-sensitive applications. Additionally,
+ * default-constructed instances do not use a cryptographically random
+ * seed unless the {@linkplain System#getProperty system property}
+ * {@code java.util.secureRandomSeed} is set to {@code true}.
+ *
+ * @author Guy Steele
+ * @author Doug Lea
+ * @since 1.8
+ */
+public final class Xoroshiro128StarStar implements LeapableRng {
+
+ /*
+ * Implementation Overview.
+ *
+ * This is an implementation of the xoroshiro128** algorithm written
+ * in 2016 by David Blackman and Sebastiano Vigna (vigna@acm.org),
+ * and updated with improved parameters in 2018.
+ * See http://xoshiro.di.unimi.it and these two papers:
+ *
+ * Sebastiano Vigna. 2016. An Experimental Exploration of Marsaglia's
+ * xorshift Generators, Scrambled. ACM Transactions on Mathematical
+ * Software 42, 4, Article 30 (June 2016), 23 pages.
+ * https://doi.org/10.1145/2845077
+ *
+ * David Blackman and Sebastiano Vigna. 2018. Scrambled Linear
+ * Pseudorandom Number Generators. Computing Research Repository (CoRR).
+ * http://arxiv.org/abs/1805.01407
+ *
+ * The jump operation moves the current generator forward by 2*64
+ * steps; this has the same effect as calling nextLong() 2**64
+ * times, but is much faster. Similarly, the leap operation moves
+ * the current generator forward by 2*96 steps; this has the same
+ * effect as calling nextLong() 2**96 times, but is much faster.
+ * The copy method may be used to make a copy of the current
+ * generator. Thus one may repeatedly and cumulatively copy and
+ * jump to produce a sequence of generators whose states are well
+ * spaced apart along the overall state cycle (indeed, the jumps()
+ * and leaps() methods each produce a stream of such generators).
+ * The generators can then be parceled out to other threads.
+ *
+ * File organization: First the non-public methods that constitute the
+ * main algorithm, then the public methods. Note that many methods are
+ * defined by classes {@code AbstractJumpableRng} and {@code AbstractRng}.
+ */
+
+ /* ---------------- static fields ---------------- */
+
+ /**
+ * The seed generator for default constructors.
+ */
+ private static final AtomicLong defaultGen = new AtomicLong(RngSupport.initialSeed());
+
+ /*
+ * The period of this generator, which is 2**128 - 1.
+ */
+ private static final BigInteger thePeriod =
+ BigInteger.ONE.shiftLeft(128).subtract(BigInteger.ONE);
+
+ /* ---------------- instance fields ---------------- */
+
+ /**
+ * The per-instance state.
+ * At least one of the two fields x0 and x1 must be nonzero.
+ */
+ private long x0, x1;
+
+ /* ---------------- constructors ---------------- */
+
+ /**
+ * Basic constructor that initializes all fields from parameters.
+ * It then adjusts the field values if necessary to ensure that
+ * all constraints on the values of fields are met.
+ */
+ public Xoroshiro128StarStar(long x0, long x1) {
+ this.x0 = x0;
+ this.x1 = x1;
+ // If x0 and x1 are both zero, we must choose nonzero values.
+ if ((x0 | x1) == 0) {
+ // At least one of the two values generated here will be nonzero.
+ this.x0 = RngSupport.mixStafford13(x0 += RngSupport.GOLDEN_RATIO_64);
+ this.x1 = (x0 += RngSupport.GOLDEN_RATIO_64);
+ }
+ }
+
+ /**
+ * Creates a new instance of {@code Xoroshiro128StarStar} using the
+ * specified {@code long} value as the initial seed. Instances of
+ * {@code Xoroshiro128StarStar} created with the same seed in the same
+ * program generate identical sequences of values.
+ *
+ * @param seed the initial seed
+ */
+ public Xoroshiro128StarStar(long seed) {
+ // Using a value with irregularly spaced 1-bits to xor the seed
+ // argument tends to improve "pedestrian" seeds such as 0 or
+ // other small integers. We may as well use SILVER_RATIO_64.
+ //
+ // The x values are then filled in as if by a SplitMix PRNG with
+ // GOLDEN_RATIO_64 as the gamma value and Stafford13 as the mixer.
+ this(RngSupport.mixStafford13(seed ^= RngSupport.SILVER_RATIO_64),
+ RngSupport.mixStafford13(seed + RngSupport.GOLDEN_RATIO_64));
+ }
+
+ /**
+ * Creates a new instance of {@code Xoroshiro128StarStar} that is likely to
+ * generate sequences of values that are statistically independent
+ * of those of any other instances in the current program execution,
+ * but may, and typically does, vary across program invocations.
+ */
+ public Xoroshiro128StarStar() {
+ // Using GOLDEN_RATIO_64 here gives us a good Weyl sequence of values.
+ this(defaultGen.getAndAdd(RngSupport.GOLDEN_RATIO_64));
+ }
+
+ /**
+ * Creates a new instance of {@code Xoroshiro128StarStar} using the specified array of
+ * initial seed bytes. Instances of {@code Xoroshiro128StarStar} created with the same
+ * seed array in the same program execution generate identical sequences of values.
+ *
+ * @param seed the initial seed
+ */
+ public Xoroshiro128StarStar(byte[] seed) {
+ // Convert the seed to 2 long values, which are not both zero.
+ long[] data = RngSupport.convertSeedBytesToLongs(seed, 2, 2);
+ long x0 = data[0], x1 = data[1];
+ this.x0 = x0;
+ this.x1 = x1;
+ }
+
+ /* ---------------- public methods ---------------- */
+
+ public Xoroshiro128StarStar copy() { return new Xoroshiro128StarStar(x0, x1); }
+
+/*
+
+To the extent possible under law, the author has dedicated all copyright
+and related and neighboring rights to this software to the public domain
+worldwide. This software is distributed without any warranty.
+
+See Series of generated values pass the TestU01 BigCrush and PractRand test suites
+ * that measure independence and uniformity properties of random number generators.
+ * (Most recently validated with
+ * version 1.2.3 of TestU01
+ * and version 0.90 of PractRand.
+ * Note that TestU01 BigCrush was used to test not only values produced by the {@code nextLong()}
+ * method but also the result of bit-reversing each value produced by {@code nextLong()}.)
+ * These tests validate only the methods for certain
+ * types and ranges, but similar properties are expected to hold, at
+ * least approximately, for others as well.
+ *
+ * The class {@code Xoshiro256StarStar} uses the {@code xoshiro256} algorithm,
+ * version 1.0 (parameters 17, 45), with the "**" scrambler (a mixing function).
+ * Its state consists of four {@code long} fields {@code x0}, {@code x1}, {@code x2},
+ * and {@code x3}, which can take on any values provided that they are not all zero.
+ * The period of this generator is 2256-1.
+ *
+ * The 64-bit values produced by the {@code nextLong()} method are equidistributed.
+ * To be precise, over the course of the cycle of length 2256-1,
+ * each nonzero {@code long} value is generated 2192 times,
+ * but the value 0 is generated only 2192-1 times.
+ * The values produced by the {@code nextInt()}, {@code nextFloat()}, and {@code nextDouble()}
+ * methods are likewise equidistributed.
+ *
+ * In fact, the 64-bit values produced by the {@code nextLong()} method are 4-equidistributed.
+ * To be precise: consider the (overlapping) length-4 subsequences of the cycle of 64-bit
+ * values produced by {@code nextLong()} (assuming no other methods are called that would
+ * affect the state). There are 2256-1 such subsequences, and each subsequence,
+ * which consists of 4 64-bit values, can have one of 2256 values. Of those
+ * 2256 subsequence values, each one is generated exactly once over the course
+ * of the entire cycle, except that the subsequence (0, 0, 0, 0) never appears.
+ * The values produced by the {@code nextInt()}, {@code nextFloat()}, and {@code nextDouble()}
+ * methods are likewise 4-equidistributed, but note that that the subsequence (0, 0, 0, 0)
+ * can also appear (but occurring somewhat less frequently than all other subsequences),
+ * because the values produced by those methods have fewer than 64 randomly chosen bits.
+ *
+ * Instances {@code Xoshiro256StarStar} are not thread-safe.
+ * They are designed to be used so that each thread as its own instance.
+ * The methods {@link #jump} and {@link #leap} and {@link #jumps} and {@link #leaps}
+ * can be used to construct new instances of {@code Xoshiro256StarStar} that traverse
+ * other parts of the state cycle.
+ *
+ * Instances of {@code Xoshiro256StarStar} are not cryptographically
+ * secure. Consider instead using {@link java.security.SecureRandom}
+ * in security-sensitive applications. Additionally,
+ * default-constructed instances do not use a cryptographically random
+ * seed unless the {@linkplain System#getProperty system property}
+ * {@code java.util.secureRandomSeed} is set to {@code true}.
+ *
+ * @author Guy Steele
+ * @since 1.9
+ */
+public final class Xoshiro256StarStar implements LeapableRng {
+
+ /*
+ * Implementation Overview.
+ *
+ * This is an implementation of the xoroshiro128** algorithm written
+ * in 2018 by David Blackman and Sebastiano Vigna (vigna@acm.org).
+ * See http://xoshiro.di.unimi.it and these two papers:
+ *
+ * Sebastiano Vigna. 2016. An Experimental Exploration of Marsaglia's
+ * xorshift Generators, Scrambled. ACM Transactions on Mathematical
+ * Software 42, 4, Article 30 (June 2016), 23 pages.
+ * https://doi.org/10.1145/2845077
+ *
+ * David Blackman and Sebastiano Vigna. 2018. Scrambled Linear
+ * Pseudorandom Number Generators. Computing Research Repository (CoRR).
+ * http://arxiv.org/abs/1805.01407
+ *
+ * The jump operation moves the current generator forward by 2*128
+ * steps; this has the same effect as calling nextLong() 2**128
+ * times, but is much faster. Similarly, the leap operation moves
+ * the current generator forward by 2*192 steps; this has the same
+ * effect as calling nextLong() 2**192 times, but is much faster.
+ * The copy method may be used to make a copy of the current
+ * generator. Thus one may repeatedly and cumulatively copy and
+ * jump to produce a sequence of generators whose states are well
+ * spaced apart along the overall state cycle (indeed, the jumps()
+ * and leaps() methods each produce a stream of such generators).
+ * The generators can then be parceled out to other threads.
+ *
+ * File organization: First static fields, then instance
+ * fields, then constructors, then instance methods.
+ */
+
+ /* ---------------- static fields ---------------- */
+
+ /**
+ * The seed generator for default constructors.
+ */
+ private static final AtomicLong defaultGen = new AtomicLong(RngSupport.initialSeed());
+
+ /*
+ * The period of this generator, which is 2**256 - 1.
+ */
+ private static final BigInteger thePeriod =
+ BigInteger.ONE.shiftLeft(256).subtract(BigInteger.ONE);
+
+ /* ---------------- instance fields ---------------- */
+
+ /**
+ * The per-instance state.
+ * At least one of the four fields x0, x1, x2, and x3 must be nonzero.
+ */
+ private long x0, x1, x2, x3;
+
+ /* ---------------- constructors ---------------- */
+
+ /**
+ * Basic constructor that initializes all fields from parameters.
+ * It then adjusts the field values if necessary to ensure that
+ * all constraints on the values of fields are met.
+ */
+ public Xoshiro256StarStar(long x0, long x1, long x2, long x3) {
+ this.x0 = x0;
+ this.x1 = x1;
+ this.x2 = x2;
+ this.x3 = x3;
+ // If x0, x1, x2, and x3 are all zero, we must choose nonzero values.
+ if ((x0 | x1 | x2 | x3) == 0) {
+ // At least three of the four values generated here will be nonzero.
+ this.x0 = RngSupport.mixStafford13(x0 += RngSupport.GOLDEN_RATIO_64);
+ this.x1 = (x0 += RngSupport.GOLDEN_RATIO_64);
+ this.x2 = (x0 += RngSupport.GOLDEN_RATIO_64);
+ this.x3 = (x0 += RngSupport.GOLDEN_RATIO_64);
+ }
+ }
+
+ /**
+ * Creates a new instance of {@code Xoshiro256StarStar} using the
+ * specified {@code long} value as the initial seed. Instances of
+ * {@code Xoshiro256StarStar} created with the same seed in the same
+ * program generate identical sequences of values.
+ *
+ * @param seed the initial seed
+ */
+ public Xoshiro256StarStar(long seed) {
+ // Using a value with irregularly spaced 1-bits to xor the seed
+ // argument tends to improve "pedestrian" seeds such as 0 or
+ // other small integers. We may as well use SILVER_RATIO_64.
+ //
+ // The x values are then filled in as if by a SplitMix PRNG with
+ // GOLDEN_RATIO_64 as the gamma value and Stafford13 as the mixer.
+ this(RngSupport.mixStafford13(seed ^= RngSupport.SILVER_RATIO_64),
+ RngSupport.mixStafford13(seed += RngSupport.GOLDEN_RATIO_64),
+ RngSupport.mixStafford13(seed += RngSupport.GOLDEN_RATIO_64),
+ RngSupport.mixStafford13(seed + RngSupport.GOLDEN_RATIO_64));
+ }
+
+ /**
+ * Creates a new instance of {@code Xoshiro256StarStar} that is likely to
+ * generate sequences of values that are statistically independent
+ * of those of any other instances in the current program execution,
+ * but may, and typically does, vary across program invocations.
+ */
+ public Xoshiro256StarStar() {
+ // Using GOLDEN_RATIO_64 here gives us a good Weyl sequence of values.
+ this(defaultGen.getAndAdd(RngSupport.GOLDEN_RATIO_64));
+ }
+
+ /**
+ * Creates a new instance of {@code Xoshiro256StarStar} using the specified array of
+ * initial seed bytes. Instances of {@code Xoshiro256StarStar} created with the same
+ * seed array in the same program execution generate identical sequences of values.
+ *
+ * @param seed the initial seed
+ */
+ public Xoshiro256StarStar(byte[] seed) {
+ // Convert the seed to 4 long values, which are not all zero.
+ long[] data = RngSupport.convertSeedBytesToLongs(seed, 4, 4);
+ long x0 = data[0], x1 = data[1], x2 = data[2], x3 = data[3];
+ this.x0 = x0;
+ this.x1 = x1;
+ this.x2 = x2;
+ this.x3 = x3;
+ }
+
+ /* ---------------- public methods ---------------- */
+
+ public Xoshiro256StarStar copy() { return new Xoshiro256StarStar(x0, x1, x2, x3); }
+
+ /**
+ * Returns a pseudorandom {@code long} value.
+ *
+ * @return a pseudorandom {@code long} value
+ */
+
+ public long nextLong() {
+ final long z = x0;
+ long q0 = x0, q1 = x1, q2 = x2, q3 = x3;
+ { long t = q1 << 17; q2 ^= q0; q3 ^= q1; q1 ^= q2; q0 ^= q3; q2 ^= t; q3 = Long.rotateLeft(q3, 45); } // xoshiro256 1.0
+ x0 = q0; x1 = q1; x2 = q2; x3 = q3;
+ return Long.rotateLeft(z * 5, 7) * 9; // "starstar" mixing function
+ }
+
+ public BigInteger period() { return thePeriod; }
+
+
+ public double defaultJumpDistance() { return 0x1.0p64; }
+ public double defaultLeapDistance() { return 0x1.0p96; }
+
+ private static final long[] JUMP_TABLE = {
+ 0x180ec6d33cfd0abaL, 0xd5a61266f0c9392cL, 0xa9582618e03fc9aaL, 0x39abdc4529b1661cL };
+
+ private static final long[] LEAP_TABLE = {
+ 0x76e15d3efefdcbbfL, 0xc5004e441c522fb3L, 0x77710069854ee241L, 0x39109bb02acbe635L };
+
+/* This is the jump function for the generator. It is equivalent
+ to 2**128 calls to next(); it can be used to generate 2**128
+ non-overlapping subsequences for parallel computations. */
+
+ public void jump() { jumpAlgorithm(JUMP_TABLE); }
+
+/* This is the long-jump function for the generator. It is equivalent to
+ 2**192 calls to next(); it can be used to generate 2**64 starting points,
+ from each of which jump() will generate 2**64 non-overlapping
+ subsequences for parallel distributed computations. */
+
+ public void leap() { jumpAlgorithm(LEAP_TABLE); }
+
+ private void jumpAlgorithm(long[] table) {
+ long s0 = 0, s1 = 0, s2 = 0, s3 = 0;
+ for (int i = 0; i < table.length; i++) {
+ for (int b = 0; b < 64; b++) {
+ if ((table[i] & (1L << b)) != 0) {
+ s0 ^= x0;
+ s1 ^= x1;
+ s2 ^= x2;
+ s3 ^= x3;
+ }
+ nextLong();
+ }
+ x0 = s0;
+ x1 = s1;
+ x2 = s2;
+ x3 = s3;
+ }
+ }
+
+}
{@code
+ * Random rnd = new Random();
+ * rnd.setSeed(seed);}
+ *
+ * @param seed the initial seed
+ * @see #setSeed(long)
+ */
+ public Random(long seed) {
+ if (getClass() == Random.class)
+ this.seed = new AtomicLong(initialScramble(seed));
+ else {
+ // subclass might have overriden setSeed
+ this.seed = new AtomicLong();
+ setSeed(seed);
+ }
+ }
+
+ private static long initialScramble(long seed) {
+ return (seed ^ multiplier) & mask;
+ }
+
+ /**
+ * Sets the seed of this random number generator using a single
+ * {@code long} seed. The general contract of {@code setSeed} is
+ * that it alters the state of this random number generator object
+ * so as to be in exactly the same state as if it had just been
+ * created with the argument {@code seed} as a seed. The method
+ * {@code setSeed} is implemented by class {@code Random} by
+ * atomically updating the seed to
+ * {@code (seed ^ 0x5DEECE66DL) & ((1L << 48) - 1)}
+ * and clearing the {@code haveNextNextGaussian} flag used by {@link
+ * #nextGaussian}.
+ *
+ * {@code (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1)}
+ * and returning
+ * {@code (int)(seed >>> (48 - bits))}.
+ *
+ * This is a linear congruential pseudorandom number generator, as
+ * defined by D. H. Lehmer and described by Donald E. Knuth in
+ * The Art of Computer Programming, Volume 3:
+ * Seminumerical Algorithms, section 3.2.1.
+ *
+ * @param bits random bits
+ * @return the next pseudorandom value from this random number
+ * generator's sequence
+ * @since 1.1
+ */
+ protected int next(int bits) {
+ long oldseed, nextseed;
+ AtomicLong seed = this.seed;
+ do {
+ oldseed = seed.get();
+ nextseed = (oldseed * multiplier + addend) & mask;
+ } while (!seed.compareAndSet(oldseed, nextseed));
+ return (int)(nextseed >>> (48 - bits));
+ }
+
+ static final BigInteger thePeriod = BigInteger.valueOf(1L<<48); // Period is 2**48
+
+ /**
+ * Returns the period of this random number generator.
+ *
+ * @return the period of this random number generator.
+ */
+ public BigInteger period() {
+ // Here we also take care of checking for instances of class SecureRandom,
+ // just so as not to bother the implementors of that class.
+ // (Any specific instance of SecureRandom can of course override this method.)
+ // The cast to (Object) is of course needed only during development.
+ return ((Object)this instanceof java.security.SecureRandom) ? Rng.HUGE_PERIOD : thePeriod;
+ }
+
+ /**
+ * Generates random bytes and places them into a user-supplied
+ * byte array. The number of random bytes produced is equal to
+ * the length of the byte array.
+ *
+ * {@code
+ * public void nextBytes(byte[] bytes) {
+ * for (int i = 0; i < bytes.length; )
+ * for (int rnd = nextInt(), n = Math.min(bytes.length - i, 4);
+ * n-- > 0; rnd >>= 8)
+ * bytes[i++] = (byte)rnd;
+ * }}
+ *
+ * @param bytes the byte array to fill with random bytes
+ * @throws NullPointerException if the byte array is null
+ * @since 1.1
+ */
+ public void nextBytes(byte[] bytes) {
+ for (int i = 0, len = bytes.length; i < len; )
+ for (int rnd = nextInt(),
+ n = Math.min(len - i, Integer.SIZE/Byte.SIZE);
+ n-- > 0; rnd >>= Byte.SIZE)
+ bytes[i++] = (byte)rnd;
+ }
+
+ /**
+ * Returns the next pseudorandom, uniformly distributed {@code int}
+ * value from this random number generator's sequence. The general
+ * contract of {@code nextInt} is that one {@code int} value is
+ * pseudorandomly generated and returned. All 232 possible
+ * {@code int} values are produced with (approximately) equal probability.
+ *
+ * {@code
+ * public int nextInt() {
+ * return next(32);
+ * }}
+ *
+ * @return the next pseudorandom, uniformly distributed {@code int}
+ * value from this random number generator's sequence
+ */
+ public int nextInt() {
+ return next(32);
+ }
+
+ /**
+ * Returns a pseudorandom {@code int} value between zero (inclusive)
+ * and the specified bound (exclusive).
+ *
+ * @param bound the upper bound (exclusive). Must be positive.
+ * @return a pseudorandom {@code int} value between zero
+ * (inclusive) and the bound (exclusive)
+ * @throws IllegalArgumentException if {@code bound} is not positive
+ */
+ public int nextInt(int bound) {
+ if (bound <= 0)
+ throw new IllegalArgumentException(BadBound);
+ // Specialize internalNextInt for origin 0
+ int r = nextInt();
+ int m = bound - 1;
+ if ((bound & m) == 0) // power of two
+ r &= m;
+ else { // reject over-represented candidates
+ for (int u = r >>> 1;
+ u + m - (r = u % bound) < 0;
+ u = nextInt() >>> 1)
+ ;
+ }
+ return r;
+ }
+
+ /**
+ * Returns the next pseudorandom, uniformly distributed {@code long}
+ * value from this random number generator's sequence. The general
+ * contract of {@code nextLong} is that one {@code long} value is
+ * pseudorandomly generated and returned.
+ *
+ * {@code
+ * public long nextLong() {
+ * return ((long)next(32) << 32) + next(32);
+ * }}
+ *
+ * Because class {@code Random} uses a seed with only 48 bits,
+ * this algorithm will not return all possible {@code long} values.
+ *
+ * @return the next pseudorandom, uniformly distributed {@code long}
+ * value from this random number generator's sequence
+ */
+ public long nextLong() {
+ // it's okay that the bottom word remains signed.
+ return ((long)(next(32)) << 32) + next(32);
+ }
+
+ /**
+ * Returns the next pseudorandom, uniformly distributed
+ * {@code boolean} value from this random number generator's
+ * sequence. The general contract of {@code nextBoolean} is that one
+ * {@code boolean} value is pseudorandomly generated and returned. The
+ * values {@code true} and {@code false} are produced with
+ * (approximately) equal probability.
+ *
+ * {@code
+ * public boolean nextBoolean() {
+ * return next(1) != 0;
+ * }}
+ *
+ * @return the next pseudorandom, uniformly distributed
+ * {@code boolean} value from this random number generator's
+ * sequence
+ * @since 1.2
+ */
+ public boolean nextBoolean() {
+ return next(1) != 0;
+ }
+
+ /**
+ * Returns the next pseudorandom, uniformly distributed {@code float}
+ * value between {@code 0.0} and {@code 1.0} from this random
+ * number generator's sequence.
+ *
+ * {@code
+ * public float nextFloat() {
+ * return next(24) / ((float)(1 << 24));
+ * }}
+ *
+ * {@code
+ * return next(30) / ((float)(1 << 30));}
+ * This might seem to be equivalent, if not better, but in fact it
+ * introduced a slight nonuniformity because of the bias in the rounding
+ * of floating-point numbers: it was slightly more likely that the
+ * low-order bit of the significand would be 0 than that it would be 1.]
+ *
+ * @return the next pseudorandom, uniformly distributed {@code float}
+ * value between {@code 0.0} and {@code 1.0} from this
+ * random number generator's sequence
+ */
+ public float nextFloat() {
+ return next(24) / ((float)(1 << 24));
+ }
+
+ /**
+ * Returns the next pseudorandom, uniformly distributed
+ * {@code double} value between {@code 0.0} and
+ * {@code 1.0} from this random number generator's sequence.
+ *
+ * {@code
+ * public double nextDouble() {
+ * return (((long)next(26) << 27) + next(27))
+ * / (double)(1L << 53);
+ * }}
+ *
+ * {@code
+ * return (((long)next(27) << 27) + next(27))
+ * / (double)(1L << 54);}
+ * This might seem to be equivalent, if not better, but in fact it
+ * introduced a large nonuniformity because of the bias in the rounding
+ * of floating-point numbers: it was three times as likely that the
+ * low-order bit of the significand would be 0 than that it would be 1!
+ * This nonuniformity probably doesn't matter much in practice, but we
+ * strive for perfection.]
+ *
+ * @return the next pseudorandom, uniformly distributed {@code double}
+ * value between {@code 0.0} and {@code 1.0} from this
+ * random number generator's sequence
+ * @see Math#random
+ */
+ public double nextDouble() {
+ return (((long)(next(26)) << 27) + next(27)) * DOUBLE_UNIT;
+ }
+
+ private double nextNextGaussian;
+ private boolean haveNextNextGaussian = false;
+
+ /**
+ * Returns the next pseudorandom, Gaussian ("normally") distributed
+ * {@code double} value with mean {@code 0.0} and standard
+ * deviation {@code 1.0} from this random number generator's sequence.
+ * {@code
+ * private double nextNextGaussian;
+ * private boolean haveNextNextGaussian = false;
+ *
+ * public double nextGaussian() {
+ * if (haveNextNextGaussian) {
+ * haveNextNextGaussian = false;
+ * return nextNextGaussian;
+ * } else {
+ * double v1, v2, s;
+ * do {
+ * v1 = 2 * nextDouble() - 1; // between -1.0 and 1.0
+ * v2 = 2 * nextDouble() - 1; // between -1.0 and 1.0
+ * s = v1 * v1 + v2 * v2;
+ * } while (s >= 1 || s == 0);
+ * double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s);
+ * nextNextGaussian = v2 * multiplier;
+ * haveNextNextGaussian = true;
+ * return v1 * multiplier;
+ * }
+ * }}
+ * This uses the polar method of G. E. P. Box, M. E. Muller, and
+ * G. Marsaglia, as described by Donald E. Knuth in The Art of
+ * Computer Programming, Volume 3: Seminumerical Algorithms,
+ * section 3.4.1, subsection C, algorithm P. Note that it generates two
+ * independent values at the cost of only one call to {@code StrictMath.log}
+ * and one call to {@code StrictMath.sqrt}.
+ *
+ * @return the next pseudorandom, Gaussian ("normally") distributed
+ * {@code double} value with mean {@code 0.0} and
+ * standard deviation {@code 1.0} from this random number
+ * generator's sequence
+ */
+ synchronized public double nextGaussian() {
+ // See Knuth, ACP, Section 3.4.1 Algorithm C.
+ if (haveNextNextGaussian) {
+ haveNextNextGaussian = false;
+ return nextNextGaussian;
+ } else {
+ double v1, v2, s;
+ do {
+ v1 = 2 * nextDouble() - 1; // between -1 and 1
+ v2 = 2 * nextDouble() - 1; // between -1 and 1
+ s = v1 * v1 + v2 * v2;
+ } while (s >= 1 || s == 0);
+ double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s);
+ nextNextGaussian = v2 * multiplier;
+ haveNextNextGaussian = true;
+ return v1 * multiplier;
+ }
+ }
+
+ /**
+ * Serializable fields for Random.
+ *
+ * @serialField seed long
+ * seed for random computations
+ * @serialField nextNextGaussian double
+ * next Gaussian to be returned
+ * @serialField haveNextNextGaussian boolean
+ * nextNextGaussian is valid
+ */
+ private static final ObjectStreamField[] serialPersistentFields = {
+ new ObjectStreamField("seed", Long.TYPE),
+ new ObjectStreamField("nextNextGaussian", Double.TYPE),
+ new ObjectStreamField("haveNextNextGaussian", Boolean.TYPE)
+ };
+
+ /**
+ * Reconstitute the {@code Random} instance from a stream (that is,
+ * deserialize it).
+ */
+ private void readObject(java.io.ObjectInputStream s)
+ throws java.io.IOException, ClassNotFoundException {
+
+ ObjectInputStream.GetField fields = s.readFields();
+
+ // The seed is read in as {@code long} for
+ // historical reasons, but it is converted to an AtomicLong.
+ long seedVal = fields.get("seed", -1L);
+ if (seedVal < 0)
+ throw new java.io.StreamCorruptedException(
+ "Random: invalid seed");
+ resetSeed(seedVal);
+ nextNextGaussian = fields.get("nextNextGaussian", 0.0);
+ haveNextNextGaussian = fields.get("haveNextNextGaussian", false);
+ }
+
+ /**
+ * Save the {@code Random} instance to a stream.
+ */
+ synchronized private void writeObject(ObjectOutputStream s)
+ throws IOException {
+
+ // set the values of the Serializable fields
+ ObjectOutputStream.PutField fields = s.putFields();
+
+ // The seed is serialized as a long for historical reasons.
+ fields.put("seed", seed.get());
+ fields.put("nextNextGaussian", nextNextGaussian);
+ fields.put("haveNextNextGaussian", haveNextNextGaussian);
+
+ // save them
+ s.writeFields();
+ }
+
+ // Support for resetting seed while deserializing
+ private static final Unsafe unsafe = Unsafe.getUnsafe();
+ private static final long seedOffset;
+ static {
+ try {
+ seedOffset = unsafe.objectFieldOffset
+ (Random.class.getDeclaredField("seed"));
+ } catch (Exception ex) { throw new Error(ex); }
+ }
+ private void resetSeed(long seedVal) {
+ unsafe.putObjectVolatile(this, seedOffset, new AtomicLong(seedVal));
+ }
+}
diff -r c646b256fbcc -r 6d87e9f7a1ec newrandom/Rng.java
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/newrandom/Rng.java Thu May 23 16:45:56 2019 -0400
@@ -0,0 +1,635 @@
+/*
+ * Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
+ * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ */
+// package java.util;
+
+import java.math.BigInteger;
+import java.util.stream.DoubleStream;
+import java.util.stream.IntStream;
+import java.util.stream.LongStream;
+
+/**
+ * The {@code Rng} interface is designed to provide a common protocol
+ * for objects that generate random or (more typically) pseudorandom
+ * sequences of numbers (or Boolean values). Such a sequence may be
+ * obtained by either repeatedly invoking a method that returns a
+ * single (pseudo)randomly chosen value, or by invoking a method that
+ * returns a stream of (pseudo)randomly chosen values.
+ *
+ *
+ *
+ *
+ *
+ * @param origin the least value that can be produced,
+ * unless greater than or equal to {@code bound}
+ * @param bound the upper bound (exclusive), unless {@code origin}
+ * is greater than or equal to {@code bound}
+ * @return a pseudorandomly chosen {@code long} value,
+ * which will be between {@code origin} (inclusive) and
+ * {@code bound} exclusive unless {@code origin}
+ * is greater than or equal to {@code bound}
+ */
+ public static long boundedNextLong(Rng rng, long origin, long bound) {
+ long r = rng.nextLong();
+ if (origin < bound) {
+ // It's not case (1).
+ final long n = bound - origin;
+ final long m = n - 1;
+ if ((n & m) == 0L) {
+ // It is case (2): length of range is a power of 2.
+ r = (r & m) + origin;
+ } else if (n > 0L) {
+ // It is case (3): need to reject over-represented candidates.
+ /* This loop takes an unlovable form (but it works):
+ because the first candidate is already available,
+ we need a break-in-the-middle construction,
+ which is concisely but cryptically performed
+ within the while-condition of a body-less for loop. */
+ for (long u = r >>> 1; // ensure nonnegative
+ u + m - (r = u % n) < 0L; // rejection check
+ u = rng.nextLong() >>> 1) // retry
+ ;
+ r += origin;
+ }
+ else {
+ // It is case (4): length of range not representable as long.
+ while (r < origin || r >= bound)
+ r = rng.nextLong();
+ }
+ }
+ return r;
+ }
+
+ /**
+ * This is the form of {@code nextLong} used by the public method
+ * {@code nextLong(bound)}. This is essentially a version of
+ * {@code boundedNextLong(origin, bound)} that has been
+ * specialized for the case where the {@code origin} is zero
+ * and the {@code bound} is greater than zero. The value
+ * returned is chosen pseudorandomly from nonnegative integer
+ * values less than {@code bound}.
+ *
+ * @implNote This method first calls {@code nextLong()} to obtain
+ * a {@code long} value that is assumed to be pseudorandomly
+ * chosen uniformly and independently from the 264
+ * possible {@code long} values (that is, each of the 264
+ * possible long values is equally likely to be chosen).
+ * Under some circumstances (when the specified range is not
+ * a power of 2), {@code nextLong()} may be called additional times
+ * to ensure that that the values in the specified range are
+ * equally likely to be chosen (provided the assumption holds).
+ *
+ *
+ *
+ *
+ *
+ * @param bound the upper bound (exclusive); must be greater than zero
+ * @return a pseudorandomly chosen {@code long} value
+ */
+ public static long boundedNextLong(Rng rng, long bound) {
+ // Specialize boundedNextLong for origin == 0, bound > 0
+ final long m = bound - 1;
+ long r = rng.nextLong();
+ if ((bound & m) == 0L) {
+ // The bound is a power of 2.
+ r &= m;
+ } else {
+ // Must reject over-represented candidates
+ /* This loop takes an unlovable form (but it works):
+ because the first candidate is already available,
+ we need a break-in-the-middle construction,
+ which is concisely but cryptically performed
+ within the while-condition of a body-less for loop. */
+ for (long u = r >>> 1;
+ u + m - (r = u % bound) < 0L;
+ u = rng.nextLong() >>> 1)
+ ;
+ }
+ return r;
+ }
+
+ /**
+ * This is the form of {@code nextInt} used by an {@code IntStream}
+ * {@code Spliterator} and by the public method
+ * {@code nextInt(origin, bound)}. If {@code origin} is greater
+ * than {@code bound}, then this method simply calls the unbounded
+ * version of {@code nextInt()}, choosing pseudorandomly from
+ * among all 264 possible {@code int} values}, and
+ * otherwise uses one or more calls to {@code nextInt()} to
+ * choose a value pseudorandomly from the possible values
+ * between {@code origin} (inclusive) and {@code bound} (exclusive).
+ *
+ * @implNote The implementation of this method is identical to
+ * the implementation of {@code nextLong(origin, bound)}
+ * except that {@code int} values and the {@code nextInt()}
+ * method are used rather than {@code long} values and the
+ * {@code nextLong()} method.
+ *
+ * @param origin the least value that can be produced,
+ * unless greater than or equal to {@code bound}
+ * @param bound the upper bound (exclusive), unless {@code origin}
+ * is greater than or equal to {@code bound}
+ * @return a pseudorandomly chosen {@code int} value,
+ * which will be between {@code origin} (inclusive) and
+ * {@code bound} exclusive unless {@code origin}
+ * is greater than or equal to {@code bound}
+ */
+ public static int boundedNextInt(Rng rng, int origin, int bound) {
+ int r = rng.nextInt();
+ if (origin < bound) {
+ // It's not case (1).
+ final int n = bound - origin;
+ final int m = n - 1;
+ if ((n & m) == 0) {
+ // It is case (2): length of range is a power of 2.
+ r = (r & m) + origin;
+ } else if (n > 0) {
+ // It is case (3): need to reject over-represented candidates.
+ for (int u = r >>> 1;
+ u + m - (r = u % n) < 0;
+ u = rng.nextInt() >>> 1)
+ ;
+ r += origin;
+ }
+ else {
+ // It is case (4): length of range not representable as long.
+ while (r < origin || r >= bound)
+
+
+ r = rng.nextInt();
+ }
+ }
+ return r;
+ }
+
+ /**
+ * This is the form of {@code nextInt} used by the public method
+ * {@code nextInt(bound)}. This is essentially a version of
+ * {@code boundedNextInt(origin, bound)} that has been
+ * specialized for the case where the {@code origin} is zero
+ * and the {@code bound} is greater than zero. The value
+ * returned is chosen pseudorandomly from nonnegative integer
+ * values less than {@code bound}.
+ *
+ * @implNote The implementation of this method is identical to
+ * the implementation of {@code nextLong(bound)}
+ * except that {@code int} values and the {@code nextInt()}
+ * method are used rather than {@code long} values and the
+ * {@code nextLong()} method.
+ *
+ * @param bound the upper bound (exclusive); must be greater than zero
+ * @return a pseudorandomly chosen {@code long} value
+ */
+ public static int boundedNextInt(Rng rng, int bound) {
+ // Specialize boundedNextInt for origin == 0, bound > 0
+ final int m = bound - 1;
+ int r = rng.nextInt();
+ if ((bound & m) == 0) {
+ // The bound is a power of 2.
+ r &= m;
+ } else {
+ // Must reject over-represented candidates
+ for (int u = r >>> 1;
+ u + m - (r = u % bound) < 0;
+ u = rng.nextInt() >>> 1)
+ ;
+ }
+ return r;
+ }
+
+ /**
+ * This is the form of {@code nextDouble} used by a {@code DoubleStream}
+ * {@code Spliterator} and by the public method
+ * {@code nextDouble(origin, bound)}. If {@code origin} is greater
+ * than {@code bound}, then this method simply calls the unbounded
+ * version of {@code nextDouble()}, and otherwise scales and translates
+ * the result of a call to {@code nextDouble()} so that it lies
+ * between {@code origin} (inclusive) and {@code bound} (exclusive).
+ *
+ * @implNote The implementation considers two cases:
+ *
+ *
+ *
+ *
+ * @param origin the least value that can be produced,
+ * unless greater than or equal to {@code bound}; must be finite
+ * @param bound the upper bound (exclusive), unless {@code origin}
+ * is greater than or equal to {@code bound}; must be finite
+ * @return a pseudorandomly chosen {@code double} value,
+ * which will be between {@code origin} (inclusive) and
+ * {@code bound} exclusive unless {@code origin}
+ * is greater than or equal to {@code bound},
+ * in which case it will be between 0.0 (inclusive)
+ * and 1.0 (exclusive)
+ */
+ public static double boundedNextDouble(Rng rng, double origin, double bound) {
+ double r = rng.nextDouble();
+ if (origin < bound) {
+ r = r * (bound - origin) + origin;
+ if (r >= bound) // may need to correct a rounding problem
+ r = Double.longBitsToDouble(Double.doubleToLongBits(bound) - 1);
+ }
+ return r;
+ }
+
+ /**
+ * This is the form of {@code nextDouble} used by the public method
+ * {@code nextDouble(bound)}. This is essentially a version of
+ * {@code boundedNextDouble(origin, bound)} that has been
+ * specialized for the case where the {@code origin} is zero
+ * and the {@code bound} is greater than zero.
+ *
+ * @implNote The result of a call to {@code nextDouble} is
+ * multiplied by {@code bound}, and then if this result is
+ * not less than {@code bound} (which can sometimes occur
+ * because of rounding), it is replaced with the largest
+ * {@code double} value that is less than {@code bound}.
+ *
+ * @param bound the upper bound (exclusive); must be finite and
+ * greater than zero
+ * @return a pseudorandomly chosen {@code double} value
+ * between zero (inclusive) and {@code bound} (exclusive)
+ */
+ public static double boundedNextDouble(Rng rng, double bound) {
+ // Specialize boundedNextDouble for origin == 0, bound > 0
+ double r = rng.nextDouble();
+ r = r * bound;
+ if (r >= bound) // may need to correct a rounding problem
+ r = Double.longBitsToDouble(Double.doubleToLongBits(bound) - 1);
+ return r;
+ }
+
+ /**
+ * This is the form of {@code nextFloat} used by a {@code FloatStream}
+ * {@code Spliterator} (if there were any) and by the public method
+ * {@code nextFloat(origin, bound)}. If {@code origin} is greater
+ * than {@code bound}, then this method simply calls the unbounded
+ * version of {@code nextFloat()}, and otherwise scales and translates
+ * the result of a call to {@code nextFloat()} so that it lies
+ * between {@code origin} (inclusive) and {@code bound} (exclusive).
+ *
+ * @implNote The implementation of this method is identical to
+ * the implementation of {@code nextDouble(origin, bound)}
+ * except that {@code float} values and the {@code nextFloat()}
+ * method are used rather than {@code double} values and the
+ * {@code nextDouble()} method.
+ *
+ * @param origin the least value that can be produced,
+ * unless greater than or equal to {@code bound}; must be finite
+ * @param bound the upper bound (exclusive), unless {@code origin}
+ * is greater than or equal to {@code bound}; must be finite
+ * @return a pseudorandomly chosen {@code float} value,
+ * which will be between {@code origin} (inclusive) and
+ * {@code bound} exclusive unless {@code origin}
+ * is greater than or equal to {@code bound},
+ * in which case it will be between 0.0 (inclusive)
+ * and 1.0 (exclusive)
+ */
+ public static float boundedNextFloat(Rng rng, float origin, float bound) {
+ float r = rng.nextFloat();
+ if (origin < bound) {
+ r = r * (bound - origin) + origin;
+ if (r >= bound) // may need to correct a rounding problem
+ r = Float.intBitsToFloat(Float.floatToIntBits(bound) - 1);
+ }
+ return r;
+ }
+
+ /**
+ * This is the form of {@code nextFloat} used by the public method
+ * {@code nextFloat(bound)}. This is essentially a version of
+ * {@code boundedNextFloat(origin, bound)} that has been
+ * specialized for the case where the {@code origin} is zero
+ * and the {@code bound} is greater than zero.
+ *
+ * @implNote The implementation of this method is identical to
+ * the implementation of {@code nextDouble(bound)}
+ * except that {@code float} values and the {@code nextFloat()}
+ * method are used rather than {@code double} values and the
+ * {@code nextDouble()} method.
+ *
+ * @param bound the upper bound (exclusive); must be finite and
+ * greater than zero
+ * @return a pseudorandomly chosen {@code float} value
+ * between zero (inclusive) and {@code bound} (exclusive)
+ */
+ public static float boundedNextFloat(Rng rng, float bound) {
+ // Specialize boundedNextFloat for origin == 0, bound > 0
+ float r = rng.nextFloat();
+ r = r * bound;
+ if (r >= bound) // may need to correct a rounding problem
+ r = Float.intBitsToFloat(Float.floatToIntBits(bound) - 1);
+ return r;
+ }
+
+ // The following decides which of two strategies initialSeed() will use.
+ private static boolean secureRandomSeedRequested() {
+ String pp = java.security.AccessController.doPrivileged(
+ new sun.security.action.GetPropertyAction(
+ "java.util.secureRandomSeed"));
+ return (pp != null && pp.equalsIgnoreCase("true"));
+ }
+
+ private static final boolean useSecureRandomSeed = secureRandomSeedRequested();
+
+ /**
+ * Returns a {@code long} value (chosen from some
+ * machine-dependent entropy source) that may be useful for
+ * initializing a source of seed values for instances of {@code Rng}
+ * created by zero-argument constructors. (This method should
+ *
+ *
+ *
+ *
+ *