# HG changeset patch # User briangoetz # Date 1559668055 14400 # Node ID b1e6bc96af3de583a81088abd55e290d7a3081b0 # Parent 0303567f1dd1c90857375c8e622c60975a63bd9f Initial commit of new RNG code from GLS diff -r 0303567f1dd1 -r b1e6bc96af3d src/java.base/share/classes/java/util/AbstractArbitrarilyJumpableRng.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/java.base/share/classes/java/util/AbstractArbitrarilyJumpableRng.java Tue Jun 04 13:07:35 2019 -0400 @@ -0,0 +1,542 @@ +/* + * Copyright (c) 2013, 2019, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +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
+ */
+public 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
+ */
+public 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.
+ *
+ * @param ah high half of the additive parameter for the LCG
+ * @param al low half of the additive parameter for the LCG
+ * @param sh high half of the initial state for the LCG
+ * @param sl low half of the initial state for the LCG
+ * @param x0 first word of the initial state for the xorshift generator
+ * @param x1 second word of the initial state for the xorshift generator
+ * @param x2 third word of the initial state for the xorshift generator
+ * @param x3 fourth word of the initial state for the xorshift generator
+ */
+ 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 0303567f1dd1 -r b1e6bc96af3d src/java.base/share/classes/java/util/L32X64MixRandom.java
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.base/share/classes/java/util/L32X64MixRandom.java Tue Jun 04 13:07:35 2019 -0400
@@ -0,0 +1,329 @@
+/*
+ * Copyright (c) 2013, 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+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.
+ *
+ * @param a additive parameter for the LCG
+ * @param s initial state for the LCG
+ * @param x0 first word of the initial state for the xorshift generator
+ * @param x1 second word of the initial state for the xorshift generator
+ */
+ 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 0303567f1dd1 -r b1e6bc96af3d src/java.base/share/classes/java/util/L64X1024MixRandom.java
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.base/share/classes/java/util/L64X1024MixRandom.java Tue Jun 04 13:07:35 2019 -0400
@@ -0,0 +1,396 @@
+/*
+ * Copyright (c) 2013, 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+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.
+ *
+ * @param a additive parameter for the LCG
+ * @param s initial state for the LCG
+ * @param x0 first word of the initial state for the xorshift generator
+ * @param x1 second word of the initial state for the xorshift generator
+ * @param x2 third word of the initial state for the xorshift generator
+ * @param x3 fourth word of the initial state for the xorshift generator
+ * @param x4 fifth word of the initial state for the xorshift generator
+ * @param x5 sixth word of the initial state for the xorshift generator
+ * @param x6 seventh word of the initial state for the xorshift generator
+ * @param x7 eight word of the initial state for the xorshift generator
+ * @param x8 ninth word of the initial state for the xorshift generator
+ * @param x9 tenth word of the initial state for the xorshift generator
+ * @param x10 eleventh word of the initial state for the xorshift generator
+ * @param x11 twelfth word of the initial state for the xorshift generator
+ * @param x12 thirteenth word of the initial state for the xorshift generator
+ * @param x13 fourteenth word of the initial state for the xorshift generator
+ * @param x14 fifteenth word of the initial state for the xorshift generator
+ * @param x15 sixteenth word of the initial state for the xorshift generator
+ */
+ 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 0303567f1dd1 -r b1e6bc96af3d src/java.base/share/classes/java/util/L64X1024Random.java
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.base/share/classes/java/util/L64X1024Random.java Tue Jun 04 13:07:35 2019 -0400
@@ -0,0 +1,393 @@
+/*
+ * Copyright (c) 2013, 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+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.
+ *
+ * @param a additive parameter for the LCG
+ * @param s initial state for the LCG
+ * @param x0 first word of the initial state for the xorshift generator
+ * @param x1 second word of the initial state for the xorshift generator
+ * @param x2 third word of the initial state for the xorshift generator
+ * @param x3 fourth word of the initial state for the xorshift generator
+ * @param x4 fifth word of the initial state for the xorshift generator
+ * @param x5 sixth word of the initial state for the xorshift generator
+ * @param x6 seventh word of the initial state for the xorshift generator
+ * @param x7 eight word of the initial state for the xorshift generator
+ * @param x8 ninth word of the initial state for the xorshift generator
+ * @param x9 tenth word of the initial state for the xorshift generator
+ * @param x10 eleventh word of the initial state for the xorshift generator
+ * @param x11 twelfth word of the initial state for the xorshift generator
+ * @param x12 thirteenth word of the initial state for the xorshift generator
+ * @param x13 fourteenth word of the initial state for the xorshift generator
+ * @param x14 fifteenth word of the initial state for the xorshift generator
+ * @param x15 sixteenth word of the initial state for the xorshift generator
+ */
+ 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 0303567f1dd1 -r b1e6bc96af3d src/java.base/share/classes/java/util/L64X128MixRandom.java
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.base/share/classes/java/util/L64X128MixRandom.java Tue Jun 04 13:07:35 2019 -0400
@@ -0,0 +1,322 @@
+/*
+ * Copyright (c) 2013, 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+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.
+ *
+ * @param a additive parameter for the LCG
+ * @param s initial state for the LCG
+ * @param x0 first word of the initial state for the xorshift generator
+ * @param x1 second word of the initial state for the xorshift generator
+ */
+ 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 0303567f1dd1 -r b1e6bc96af3d src/java.base/share/classes/java/util/L64X128Random.java
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.base/share/classes/java/util/L64X128Random.java Tue Jun 04 13:07:35 2019 -0400
@@ -0,0 +1,318 @@
+/*
+ * Copyright (c) 2013, 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+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.
+ *
+ * @param a additive parameter for the LCG
+ * @param s initial state for the LCG
+ * @param x0 first word of the initial state for the xorshift generator
+ * @param x1 second word of the initial state for the xorshift generator
+ */
+ 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 0303567f1dd1 -r b1e6bc96af3d src/java.base/share/classes/java/util/L64X256MixRandom.java
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.base/share/classes/java/util/L64X256MixRandom.java Tue Jun 04 13:07:35 2019 -0400
@@ -0,0 +1,334 @@
+/*
+ * Copyright (c) 2013, 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+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.
+ *
+ * @param a additive parameter for the LCG
+ * @param s initial state for the LCG
+ * @param x0 first word of the initial state for the xorshift generator
+ * @param x1 second word of the initial state for the xorshift generator
+ * @param x2 third word of the initial state for the xorshift generator
+ * @param x3 fourth word of the initial state for the xorshift generator
+ */
+ 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 0303567f1dd1 -r b1e6bc96af3d src/java.base/share/classes/java/util/L64X256Random.java
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.base/share/classes/java/util/L64X256Random.java Tue Jun 04 13:07:35 2019 -0400
@@ -0,0 +1,332 @@
+/*
+ * Copyright (c) 2013, 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+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.
+ *
+ * @param a additive parameter for the LCG
+ * @param s initial state for the LCG
+ * @param x0 first word of the initial state for the xorshift generator
+ * @param x1 second word of the initial state for the xorshift generator
+ * @param x2 third word of the initial state for the xorshift generator
+ * @param x3 fourth word of the initial state for the xorshift generator
+ */
+ 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 0303567f1dd1 -r b1e6bc96af3d src/java.base/share/classes/java/util/LeapableRng.java
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.base/share/classes/java/util/LeapableRng.java Tue Jun 04 13:07:35 2019 -0400
@@ -0,0 +1,151 @@
+/*
+ * Copyright (c) 2013, 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+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 leap to
+ * a very distant point in the state cycle.
+ *
+ * Typically one will construct a series of {@code LeapableRng} objects
+ * by iterative leaping from a single original {@code LeapableRng}
+ * object, and then for each such object produce a subseries of objects
+ * by iterative jumping. There is little conceptual difference between
+ * leaping and jumping, but typically a leap will be a very long jump
+ * in the state cycle (perhaps distance 2128 or so).
+ *
+ * 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
+ */
+public 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.
+ *
+ * See http://simul.iro.umontreal.ca/rng/MRG32k3a.c .
+ *
+ * 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
+ */
+ private 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();
+ }
+ }
+
+ private 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;
+ }
+
+ /**
+ * All arguments must be known to be nonnegative integral values
+ * less than the appropriate modulus.
+ */
+ 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 = this.s11 = this.s12 = 12345.0;
+ }
+ if ((s20 == 0.0) && (s21 == 0.0) && (s22 == 0.0)) {
+ this.s20 = this.s21 = this.s21 = 12345.0;
+ }
+ }
+
+ /* ---------------- public methods ---------------- */
+
+ /**
+ * Creates a new MRG32k3a instance using six specified {@code int}
+ * initial seed values. MRG32k3a instances created with the same
+ * seeds in the same program generate identical sequences of values.
+ * If all six seed values are zero, the generator is seeded to a
+ * widely used initialization of MRG32k3a: all six state variables
+ * are set to 12345.
+ *
+ * @param s10 the first seed value for the first subgenerator
+ * @param s11 the second seed value for the first subgenerator
+ * @param s12 the third seed value for the first subgenerator
+ * @param s20 the first seed value for the second subgenerator
+ * @param s21 the second seed value for the second subgenerator
+ * @param s22 the third seed value for the second subgenerator
+ */
+ 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 = this.s11 = this.s12 = 12345.0;
+ }
+ if ((s20 == 0.0) && (s21 == 0.0) && (s22 == 0.0)) {
+ this.s20 = this.s21 = this.s21 = 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 0303567f1dd1 -r b1e6bc96af3d src/java.base/share/classes/java/util/Random.java
--- a/src/java.base/share/classes/java/util/Random.java Tue Jun 04 12:57:31 2019 -0400
+++ b/src/java.base/share/classes/java/util/Random.java Tue Jun 04 13:07:35 2019 -0400
@@ -1,30 +1,32 @@
/*
- * Copyright (c) 1995, 2018, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ * Copyright (c) 1995, 2013, 2019, Oracle and/or its affiliates. All rights reserved.
+ * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
+ *
+ *
*
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
+ *
+ *
+ *
+ *
+ *
*
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
+ *
+ *
+ *
+ *
+ *
*
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ *
*
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
+ *
+ *
*/
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;
@@ -74,7 +76,7 @@
* @since 1.0
*/
public
-class Random implements java.io.Serializable {
+class Random extends AbstractSharedRng implements java.io.Serializable {
/** use serialVersionUID from JDK 1.1 for interoperability */
static final long serialVersionUID = 3905348978240129619L;
@@ -205,6 +207,21 @@
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
@@ -233,82 +250,6 @@
}
/**
- * The form of nextLong used by LongStream Spliterators. If
- * origin is greater than bound, acts as unbounded form of
- * nextLong, else as bounded form.
- *
- * @param origin the least value, unless greater than bound
- * @param bound the upper bound (exclusive), must not equal origin
- * @return a pseudorandom value
- */
- final long internalNextLong(long origin, long bound) {
- long r = nextLong();
- if (origin < bound) {
- long n = bound - origin, m = n - 1;
- if ((n & m) == 0L) // power of two
- r = (r & m) + origin;
- else if (n > 0L) { // reject over-represented candidates
- for (long u = r >>> 1; // ensure nonnegative
- u + m - (r = u % n) < 0L; // rejection check
- u = nextLong() >>> 1) // retry
- ;
- r += origin;
- }
- else { // range not representable as long
- while (r < origin || r >= bound)
- r = nextLong();
- }
- }
- return r;
- }
-
- /**
- * The form of nextInt used by IntStream Spliterators.
- * For the unbounded case: uses nextInt().
- * For the bounded case with representable range: uses nextInt(int bound)
- * For the bounded case with unrepresentable range: uses nextInt()
- *
- * @param origin the least value, unless greater than bound
- * @param bound the upper bound (exclusive), must not equal origin
- * @return a pseudorandom value
- */
- final int internalNextInt(int origin, int bound) {
- if (origin < bound) {
- int n = bound - origin;
- if (n > 0) {
- return nextInt(n) + origin;
- }
- else { // range not representable as int
- int r;
- do {
- r = nextInt();
- } while (r < origin || r >= bound);
- return r;
- }
- }
- else {
- return nextInt();
- }
- }
-
- /**
- * The form of nextDouble used by DoubleStream Spliterators.
- *
- * @param origin the least value, unless greater than bound
- * @param bound the upper bound (exclusive), must not equal origin
- * @return a pseudorandom value
- */
- final double internalNextDouble(double origin, double bound) {
- double r = nextDouble();
- if (origin < bound) {
- r = r * (bound - origin) + origin;
- if (r >= bound) // correct for rounding
- r = Double.longBitsToDouble(Double.doubleToLongBits(bound) - 1);
- }
- return r;
- }
-
- /**
* 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
@@ -330,71 +271,26 @@
}
/**
- * Returns a pseudorandom, uniformly distributed {@code int} value
- * between 0 (inclusive) and the specified value (exclusive), drawn from
- * this random number generator's sequence. The general contract of
- * {@code nextInt} is that one {@code int} value in the specified range
- * is pseudorandomly generated and returned. All {@code bound} possible
- * {@code int} values are produced with (approximately) equal
- * probability. The method {@code nextInt(int bound)} 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 int}
- * values from the stated range with perfect uniformity.
- *
- * The algorithm is slightly tricky. It rejects values that would result
- * in an uneven distribution (due to the fact that 2^31 is not divisible
- * by n). The probability of a value being rejected depends on n. The
- * worst case is n=2^30+1, for which the probability of a reject is 1/2,
- * and the expected number of iterations before the loop terminates is 2.
- *
- * The algorithm treats the case where n is a power of two specially: it
- * returns the correct number of high-order bits from the underlying
- * pseudo-random number generator. In the absence of special treatment,
- * the correct number of low-order bits would be returned. Linear
- * congruential pseudo-random number generators such as the one
- * implemented by this class are known to have short periods in the
- * sequence of values of their low-order bits. Thus, this special case
- * greatly increases the length of the sequence of values returned by
- * successive calls to this method if n is a small power of two.
+ * Returns a pseudorandom {@code int} value between zero (inclusive)
+ * and the specified bound (exclusive).
*
* @param bound the upper bound (exclusive). Must be positive.
- * @return the next pseudorandom, uniformly distributed {@code int}
- * value between zero (inclusive) and {@code bound} (exclusive)
- * from this random number generator's sequence
- * @throws IllegalArgumentException if bound is not positive
- * @since 1.2
+ * @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);
-
- int r = next(31);
+ // Specialize internalNextInt for origin 0
+ int r = nextInt();
int m = bound - 1;
- if ((bound & m) == 0) // i.e., bound is a power of 2
- r = (int)((bound * (long)r) >> 31);
- else {
- for (int u = r;
- u - (r = u % bound) + m < 0;
- u = next(31))
+ 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;
@@ -599,565 +495,6 @@
}
}
- // stream methods, coded in a way intended to better isolate for
- // maintenance purposes the small differences across forms.
-
- /**
- * Returns a stream producing the given {@code streamSize} number of
- * pseudorandom {@code int} values.
- *
- * A pseudorandom {@code int} value is generated as if it's the result of
- * calling the method {@link #nextInt()}.
- *
- * @param streamSize the number of values to generate
- * @return a stream of pseudorandom {@code int} values
- * @throws IllegalArgumentException if {@code streamSize} is
- * less than zero
- * @since 1.8
- */
- public IntStream ints(long streamSize) {
- if (streamSize < 0L)
- throw new IllegalArgumentException(BadSize);
- return StreamSupport.intStream
- (new RandomIntsSpliterator
- (this, 0L, streamSize, Integer.MAX_VALUE, 0),
- false);
- }
-
- /**
- * Returns an effectively unlimited stream of pseudorandom {@code int}
- * values.
- *
- * A pseudorandom {@code int} value is generated as if it's the result of
- * calling the method {@link #nextInt()}.
- *
- * @implNote This method is implemented to be equivalent to {@code
- * ints(Long.MAX_VALUE)}.
- *
- * @return a stream of pseudorandom {@code int} values
- * @since 1.8
- */
- public IntStream ints() {
- return StreamSupport.intStream
- (new RandomIntsSpliterator
- (this, 0L, Long.MAX_VALUE, Integer.MAX_VALUE, 0),
- false);
- }
-
- /**
- * Returns a stream producing the given {@code streamSize} number
- * of pseudorandom {@code int} values, each conforming to the given
- * origin (inclusive) and bound (exclusive).
- *
- * A pseudorandom {@code int} value is generated as if it's the result of
- * calling the following method with the origin and bound:
- * A pseudorandom {@code int} value is generated as if it's the result of
- * calling the following method with the origin and bound:
- * A pseudorandom {@code long} value is generated as if it's the result
- * of calling the method {@link #nextLong()}.
- *
- * @param streamSize the number of values to generate
- * @return a stream of pseudorandom {@code long} values
- * @throws IllegalArgumentException if {@code streamSize} is
- * less than zero
- * @since 1.8
- */
- public LongStream longs(long streamSize) {
- if (streamSize < 0L)
- throw new IllegalArgumentException(BadSize);
- return StreamSupport.longStream
- (new RandomLongsSpliterator
- (this, 0L, streamSize, Long.MAX_VALUE, 0L),
- false);
- }
-
- /**
- * Returns an effectively unlimited stream of pseudorandom {@code long}
- * values.
- *
- * A pseudorandom {@code long} value is generated as if it's the result
- * of calling the method {@link #nextLong()}.
- *
- * @implNote This method is implemented to be equivalent to {@code
- * longs(Long.MAX_VALUE)}.
- *
- * @return a stream of pseudorandom {@code long} values
- * @since 1.8
- */
- public LongStream longs() {
- return StreamSupport.longStream
- (new RandomLongsSpliterator
- (this, 0L, Long.MAX_VALUE, Long.MAX_VALUE, 0L),
- false);
- }
-
- /**
- * Returns a stream producing the given {@code streamSize} number of
- * pseudorandom {@code long}, each conforming to the given origin
- * (inclusive) and bound (exclusive).
- *
- * A pseudorandom {@code long} value is generated as if it's the result
- * of calling the following method with the origin and bound:
- * A pseudorandom {@code long} value is generated as if it's the result
- * of calling the following method with the origin and bound:
- * A pseudorandom {@code double} value is generated as if it's the result
- * of calling the method {@link #nextDouble()}.
- *
- * @param streamSize the number of values to generate
- * @return a stream of {@code double} values
- * @throws IllegalArgumentException if {@code streamSize} is
- * less than zero
- * @since 1.8
- */
- public DoubleStream doubles(long streamSize) {
- if (streamSize < 0L)
- throw new IllegalArgumentException(BadSize);
- return StreamSupport.doubleStream
- (new RandomDoublesSpliterator
- (this, 0L, streamSize, Double.MAX_VALUE, 0.0),
- false);
- }
-
- /**
- * Returns an effectively unlimited stream of pseudorandom {@code
- * double} values, each between zero (inclusive) and one
- * (exclusive).
- *
- * A pseudorandom {@code double} value is generated as if it's the result
- * of calling the method {@link #nextDouble()}.
- *
- * @implNote This method is implemented to be equivalent to {@code
- * doubles(Long.MAX_VALUE)}.
- *
- * @return a stream of pseudorandom {@code double} values
- * @since 1.8
- */
- public DoubleStream doubles() {
- return StreamSupport.doubleStream
- (new RandomDoublesSpliterator
- (this, 0L, Long.MAX_VALUE, Double.MAX_VALUE, 0.0),
- false);
- }
-
- /**
- * Returns a stream producing the given {@code streamSize} number of
- * pseudorandom {@code double} values, each conforming to the given origin
- * (inclusive) and bound (exclusive).
- *
- * A pseudorandom {@code double} value is generated as if it's the result
- * of calling the following method with the origin and bound:
- * A pseudorandom {@code double} value is generated as if it's the result
- * of calling the following method with the origin and bound:
- * 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 2w values between 0.0 (inclusive)
+ * and 1.0 (exclusive), where w is 23 for {@code float}
+ * values and 52 for {@code double} values, such that adjacent values
+ * differ by 2−w; if an explicit range is
+ * specified, then the chosen number is computationally scaled and
+ * translated so as to appear to have been chosen from that range.
+ *
+ * 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
+ * period. (Some implementations of the {@code Rng} interface
+ * may be truly random rather than pseudorandom, for example relying
+ * on the statistical behavior of a physical object to derive chosen
+ * values. Such implementations do not have a fixed period.)
+ *
+ * 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
+ */
+
+public 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 (square root of the variance)
+ * of the Gaussian distribution to be drawn from
+ * @return a {@code double} value pseudorandomly chosen from the
+ * specified Gaussian distribution
+ * @throws IllegalArgumentException if {@code stddev} is negative
+ */
+ default double nextGaussian(double mean, double stddev) {
+ if (stddev < 0.0) throw new IllegalArgumentException("standard deviation must be non-negative");
+ return mean + stddev * RngSupport.computeNextGaussian(this);
+ }
+
+ /**
+ * 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 0303567f1dd1 -r b1e6bc96af3d src/java.base/share/classes/java/util/RngSupport.java
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.base/share/classes/java/util/RngSupport.java Tue Jun 04 13:07:35 2019 -0400
@@ -0,0 +1,1072 @@
+/*
+ * Copyright (c) 2013, 2019, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package java.util;
+
+import java.util.Rng;
+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);
+ }
+
+ /**
+ * Given an array of seed bytes of any length, construct an array
+ * of {@code long} seed values of length {@code n}, such that the
+ * last {@code z} values are not all zero.
+ *
+ * @param seed an array of {@code byte} values
+ * @param n the length of the result array (should be nonnegative)
+ * @param z the number of trailing result elements that are required
+ * to be not all zero (should be nonnegative but not larger
+ * than {@code n})
+ * @return an array of length {@code n} containing {@code long} seed values
+ */
+ 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;
+ }
+
+ /**
+ * Given an array of seed bytes of any length, construct an array
+ * of {@code int} seed values of length {@code n}, such that the
+ * last {@code z} values are not all zero.
+ *
+ * @param seed an array of {@code byte} values
+ * @param n the length of the result array (should be nonnegative)
+ * @param z the number of trailing result elements that are required
+ * to be not all zero (should be nonnegative but not larger
+ * than {@code n})
+ * @return an array of length {@code n} containing {@code int} seed values
+ */
+ 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:
+ * 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
+ */
+public 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
+ */
+
+public 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 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.
+ *
+ * @param x0 first word of the initial state
+ * @param x1 second word of the initial state
+ */
+ 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.
+ *
+ * @param x0 first word of the initial state
+ * @param x1 second word of the initial state
+ */
+ 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.
+ *
+ * @param x0 first word of the initial state
+ * @param x1 second word of the initial state
+ * @param x2 third word of the initial state
+ * @param x3 fourth word of the initial state
+ */
+ 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;
+ }
+ }
+
+}
diff -r 0303567f1dd1 -r b1e6bc96af3d src/java.base/share/classes/java/util/concurrent/ThreadLocalRandom.java
--- a/src/java.base/share/classes/java/util/concurrent/ThreadLocalRandom.java Tue Jun 04 12:57:31 2019 -0400
+++ b/src/java.base/share/classes/java/util/concurrent/ThreadLocalRandom.java Tue Jun 04 13:07:35 2019 -0400
@@ -31,6 +31,9 @@
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/publicdomain/zero/1.0/
+ *
+ * Additional modifications by Guy Steele in 2019 to refactor the code
+ * and to implement the {@code Rng} interface.
*/
package java.util.concurrent;
@@ -38,16 +41,10 @@
import java.io.ObjectStreamField;
import java.security.AccessControlContext;
import java.util.Random;
+import java.util.RngSupport;
import java.util.Spliterator;
import java.util.concurrent.atomic.AtomicInteger;
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 jdk.internal.misc.Unsafe;
import jdk.internal.misc.VM;
@@ -123,19 +120,12 @@
* 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.
+ * This implementation of ThreadLocalRandom overrides the
+ * definition of the nextGaussian() method in the class Random,
+ * and instead uses the ziggurat-based algorithm that is the
+ * default for the Rng interface.
*/
- private static long mix64(long z) {
- z = (z ^ (z >>> 33)) * 0xff51afd7ed558ccdL;
- z = (z ^ (z >>> 33)) * 0xc4ceb9fe1a85ec53L;
- return z ^ (z >>> 33);
- }
-
private static int mix32(long z) {
z = (z ^ (z >>> 33)) * 0xff51afd7ed558ccdL;
return (int)(((z ^ (z >>> 33)) * 0xc4ceb9fe1a85ec53L) >>> 32);
@@ -162,7 +152,7 @@
static final void localInit() {
int p = probeGenerator.addAndGet(PROBE_INCREMENT);
int probe = (p == 0) ? 1 : p; // skip 0
- long seed = mix64(seeder.getAndAdd(SEEDER_INCREMENT));
+ long seed = RngSupport.mixMurmur64(seeder.getAndAdd(SEEDER_INCREMENT));
Thread t = Thread.currentThread();
U.putLong(t, SEED, seed);
U.putInt(t, PROBE, probe);
@@ -212,82 +202,6 @@
}
/**
- * The form of nextLong used by LongStream Spliterators. If
- * origin is greater than bound, acts as unbounded form of
- * nextLong, else as bounded form.
- *
- * @param origin the least value, unless greater than bound
- * @param bound the upper bound (exclusive), must not equal origin
- * @return a pseudorandom value
- */
- final long internalNextLong(long origin, long bound) {
- long r = mix64(nextSeed());
- if (origin < bound) {
- long n = bound - origin, m = n - 1;
- if ((n & m) == 0L) // power of two
- r = (r & m) + origin;
- else if (n > 0L) { // reject over-represented candidates
- for (long u = r >>> 1; // ensure nonnegative
- u + m - (r = u % n) < 0L; // rejection check
- u = mix64(nextSeed()) >>> 1) // retry
- ;
- r += origin;
- }
- else { // range not representable as long
- while (r < origin || r >= bound)
- r = mix64(nextSeed());
- }
- }
- return r;
- }
-
- /**
- * 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
- */
- final int internalNextInt(int origin, int bound) {
- int r = mix32(nextSeed());
- if (origin < bound) {
- int n = bound - origin, m = n - 1;
- if ((n & m) == 0)
- r = (r & m) + origin;
- else if (n > 0) {
- for (int u = r >>> 1;
- u + m - (r = u % n) < 0;
- u = mix32(nextSeed()) >>> 1)
- ;
- r += origin;
- }
- else {
- while (r < origin || r >= bound)
- r = mix32(nextSeed());
- }
- }
- return r;
- }
-
- /**
- * The form of nextDouble used by DoubleStream Spliterators.
- *
- * @param origin the least value, unless greater than bound
- * @param bound the upper bound (exclusive), must not equal origin
- * @return a pseudorandom value
- */
- final double internalNextDouble(double origin, double bound) {
- double r = (nextLong() >>> 11) * DOUBLE_UNIT;
- if (origin < bound) {
- r = r * (bound - origin) + origin;
- if (r >= bound) // correct for rounding
- r = Double.longBitsToDouble(Double.doubleToLongBits(bound) - 1);
- }
- return r;
- }
-
- /**
* Returns a pseudorandom {@code int} value.
*
* @return a pseudorandom {@code int} value
@@ -297,622 +211,14 @@
}
/**
- * 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(BAD_BOUND);
- int r = mix32(nextSeed());
- 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 = mix32(nextSeed()) >>> 1)
- ;
- }
- return r;
- }
-
- /**
- * Returns a pseudorandom {@code int} value between the specified
- * origin (inclusive) and the specified bound (exclusive).
- *
- * @param origin the least value returned
- * @param bound the upper bound (exclusive)
- * @return a pseudorandom {@code int} value between the origin
- * (inclusive) and the bound (exclusive)
- * @throws IllegalArgumentException if {@code origin} is greater than
- * or equal to {@code bound}
- */
- public int nextInt(int origin, int bound) {
- if (origin >= bound)
- throw new IllegalArgumentException(BAD_RANGE);
- return internalNextInt(origin, bound);
- }
-
- /**
* Returns a pseudorandom {@code long} value.
*
* @return a pseudorandom {@code long} value
*/
public long nextLong() {
- return mix64(nextSeed());
- }
-
- /**
- * Returns a pseudorandom {@code long} value between zero (inclusive)
- * and the specified bound (exclusive).
- *
- * @param bound the upper bound (exclusive). Must be positive.
- * @return a pseudorandom {@code long} value between zero
- * (inclusive) and the bound (exclusive)
- * @throws IllegalArgumentException if {@code bound} is not positive
- */
- public long nextLong(long bound) {
- if (bound <= 0)
- throw new IllegalArgumentException(BAD_BOUND);
- long r = mix64(nextSeed());
- long m = bound - 1;
- if ((bound & m) == 0L) // power of two
- r &= m;
- else { // reject over-represented candidates
- for (long u = r >>> 1;
- u + m - (r = u % bound) < 0L;
- u = mix64(nextSeed()) >>> 1)
- ;
- }
- return r;
- }
-
- /**
- * Returns a pseudorandom {@code long} value between the specified
- * origin (inclusive) and the specified bound (exclusive).
- *
- * @param origin the least value returned
- * @param bound the upper bound (exclusive)
- * @return a pseudorandom {@code long} value between the origin
- * (inclusive) and the bound (exclusive)
- * @throws IllegalArgumentException if {@code origin} is greater than
- * or equal to {@code bound}
- */
- public long nextLong(long origin, long bound) {
- if (origin >= bound)
- throw new IllegalArgumentException(BAD_RANGE);
- return internalNextLong(origin, bound);
- }
-
- /**
- * 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() {
- return (mix64(nextSeed()) >>> 11) * DOUBLE_UNIT;
- }
-
- /**
- * Returns a pseudorandom {@code double} value between 0.0
- * (inclusive) and the specified bound (exclusive).
- *
- * @param bound the upper bound (exclusive). Must be positive.
- * @return a pseudorandom {@code double} value between zero
- * (inclusive) and the bound (exclusive)
- * @throws IllegalArgumentException if {@code bound} is not positive
- */
- public double nextDouble(double bound) {
- if (!(bound > 0.0))
- throw new IllegalArgumentException(BAD_BOUND);
- double result = (mix64(nextSeed()) >>> 11) * DOUBLE_UNIT * bound;
- return (result < bound) ? result : // correct for rounding
- Double.longBitsToDouble(Double.doubleToLongBits(bound) - 1);
- }
-
- /**
- * Returns a pseudorandom {@code double} value between the specified
- * origin (inclusive) and bound (exclusive).
- *
- * @param origin the least value returned
- * @param bound the upper bound (exclusive)
- * @return a pseudorandom {@code double} value between the origin
- * (inclusive) and the bound (exclusive)
- * @throws IllegalArgumentException if {@code origin} is greater than
- * or equal to {@code bound}
- */
- public double nextDouble(double origin, double bound) {
- if (!(origin < bound))
- throw new IllegalArgumentException(BAD_RANGE);
- return internalNextDouble(origin, bound);
- }
-
- /**
- * Returns a pseudorandom {@code boolean} value.
- *
- * @return a pseudorandom {@code boolean} value
- */
- public boolean nextBoolean() {
- return mix32(nextSeed()) < 0;
- }
-
- /**
- * 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 (mix32(nextSeed()) >>> 8) * FLOAT_UNIT;
- }
-
- public double nextGaussian() {
- // Use nextLocalGaussian instead of nextGaussian field
- Double d = nextLocalGaussian.get();
- if (d != null) {
- nextLocalGaussian.set(null);
- return d.doubleValue();
- }
- 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);
- nextLocalGaussian.set(Double.valueOf(v2 * multiplier));
- return v1 * multiplier;
- }
-
- // stream methods, coded in a way intended to better isolate for
- // maintenance purposes the small differences across forms.
-
- /**
- * Returns a stream producing the given {@code streamSize} number of
- * pseudorandom {@code int} values.
- *
- * @param streamSize the number of values to generate
- * @return a stream of pseudorandom {@code int} values
- * @throws IllegalArgumentException if {@code streamSize} is
- * less than zero
- * @since 1.8
- */
- public IntStream ints(long streamSize) {
- if (streamSize < 0L)
- throw new IllegalArgumentException(BAD_SIZE);
- return StreamSupport.intStream
- (new RandomIntsSpliterator
- (0L, streamSize, Integer.MAX_VALUE, 0),
- false);
- }
-
- /**
- * Returns an effectively unlimited stream of pseudorandom {@code int}
- * values.
- *
- * @implNote This method is implemented to be equivalent to {@code
- * ints(Long.MAX_VALUE)}.
- *
- * @return a stream of pseudorandom {@code int} values
- * @since 1.8
- */
- public IntStream ints() {
- return StreamSupport.intStream
- (new RandomIntsSpliterator
- (0L, Long.MAX_VALUE, Integer.MAX_VALUE, 0),
- false);
- }
-
- /**
- * Returns a stream producing the given {@code streamSize} number
- * of pseudorandom {@code int} values, each conforming to the given
- * origin (inclusive) and bound (exclusive).
- *
- * @param streamSize the number of values to generate
- * @param randomNumberOrigin the origin (inclusive) of each random value
- * @param randomNumberBound the bound (exclusive) of each random value
- * @return a stream of pseudorandom {@code int} values,
- * each with the given origin (inclusive) and bound (exclusive)
- * @throws IllegalArgumentException if {@code streamSize} is
- * less than zero, or {@code randomNumberOrigin}
- * is greater than or equal to {@code randomNumberBound}
- * @since 1.8
- */
- public IntStream ints(long streamSize, int randomNumberOrigin,
- int randomNumberBound) {
- if (streamSize < 0L)
- throw new IllegalArgumentException(BAD_SIZE);
- if (randomNumberOrigin >= randomNumberBound)
- throw new IllegalArgumentException(BAD_RANGE);
- return StreamSupport.intStream
- (new RandomIntsSpliterator
- (0L, streamSize, randomNumberOrigin, randomNumberBound),
- false);
- }
-
- /**
- * Returns an effectively unlimited stream of pseudorandom {@code
- * int} values, each conforming to the given origin (inclusive) and bound
- * (exclusive).
- *
- * @implNote This method is implemented to be equivalent to {@code
- * ints(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
- *
- * @param randomNumberOrigin the origin (inclusive) of each random value
- * @param randomNumberBound the bound (exclusive) of each random value
- * @return a stream of pseudorandom {@code int} values,
- * each with the given origin (inclusive) and bound (exclusive)
- * @throws IllegalArgumentException if {@code randomNumberOrigin}
- * is greater than or equal to {@code randomNumberBound}
- * @since 1.8
- */
- public IntStream ints(int randomNumberOrigin, int randomNumberBound) {
- if (randomNumberOrigin >= randomNumberBound)
- throw new IllegalArgumentException(BAD_RANGE);
- return StreamSupport.intStream
- (new RandomIntsSpliterator
- (0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
- false);
- }
-
- /**
- * Returns a stream producing the given {@code streamSize} number of
- * pseudorandom {@code long} values.
- *
- * @param streamSize the number of values to generate
- * @return a stream of pseudorandom {@code long} values
- * @throws IllegalArgumentException if {@code streamSize} is
- * less than zero
- * @since 1.8
- */
- public LongStream longs(long streamSize) {
- if (streamSize < 0L)
- throw new IllegalArgumentException(BAD_SIZE);
- return StreamSupport.longStream
- (new RandomLongsSpliterator
- (0L, streamSize, Long.MAX_VALUE, 0L),
- false);
- }
-
- /**
- * Returns an effectively unlimited stream of pseudorandom {@code long}
- * values.
- *
- * @implNote This method is implemented to be equivalent to {@code
- * longs(Long.MAX_VALUE)}.
- *
- * @return a stream of pseudorandom {@code long} values
- * @since 1.8
- */
- public LongStream longs() {
- return StreamSupport.longStream
- (new RandomLongsSpliterator
- (0L, Long.MAX_VALUE, Long.MAX_VALUE, 0L),
- false);
- }
-
- /**
- * Returns a stream producing the given {@code streamSize} number of
- * pseudorandom {@code long}, each conforming to the given origin
- * (inclusive) and bound (exclusive).
- *
- * @param streamSize the number of values to generate
- * @param randomNumberOrigin the origin (inclusive) of each random value
- * @param randomNumberBound the bound (exclusive) of each random value
- * @return a stream of pseudorandom {@code long} values,
- * each with the given origin (inclusive) and bound (exclusive)
- * @throws IllegalArgumentException if {@code streamSize} is
- * less than zero, or {@code randomNumberOrigin}
- * is greater than or equal to {@code randomNumberBound}
- * @since 1.8
- */
- public LongStream longs(long streamSize, long randomNumberOrigin,
- long randomNumberBound) {
- if (streamSize < 0L)
- throw new IllegalArgumentException(BAD_SIZE);
- if (randomNumberOrigin >= randomNumberBound)
- throw new IllegalArgumentException(BAD_RANGE);
- return StreamSupport.longStream
- (new RandomLongsSpliterator
- (0L, streamSize, randomNumberOrigin, randomNumberBound),
- false);
+ return RngSupport.mixMurmur64(nextSeed());
}
- /**
- * Returns an effectively unlimited stream of pseudorandom {@code
- * long} values, each conforming to the given origin (inclusive) and bound
- * (exclusive).
- *
- * @implNote This method is implemented to be equivalent to {@code
- * longs(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
- *
- * @param randomNumberOrigin the origin (inclusive) of each random value
- * @param randomNumberBound the bound (exclusive) of each random value
- * @return a stream of pseudorandom {@code long} values,
- * each with the given origin (inclusive) and bound (exclusive)
- * @throws IllegalArgumentException if {@code randomNumberOrigin}
- * is greater than or equal to {@code randomNumberBound}
- * @since 1.8
- */
- public LongStream longs(long randomNumberOrigin, long randomNumberBound) {
- if (randomNumberOrigin >= randomNumberBound)
- throw new IllegalArgumentException(BAD_RANGE);
- return StreamSupport.longStream
- (new RandomLongsSpliterator
- (0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
- false);
- }
-
- /**
- * Returns a stream producing the given {@code streamSize} number of
- * pseudorandom {@code double} values, each between zero
- * (inclusive) and one (exclusive).
- *
- * @param streamSize the number of values to generate
- * @return a stream of {@code double} values
- * @throws IllegalArgumentException if {@code streamSize} is
- * less than zero
- * @since 1.8
- */
- public DoubleStream doubles(long streamSize) {
- if (streamSize < 0L)
- throw new IllegalArgumentException(BAD_SIZE);
- return StreamSupport.doubleStream
- (new RandomDoublesSpliterator
- (0L, streamSize, Double.MAX_VALUE, 0.0),
- false);
- }
-
- /**
- * Returns an effectively unlimited stream of pseudorandom {@code
- * double} values, each between zero (inclusive) and one
- * (exclusive).
- *
- * @implNote This method is implemented to be equivalent to {@code
- * doubles(Long.MAX_VALUE)}.
- *
- * @return a stream of pseudorandom {@code double} values
- * @since 1.8
- */
- public DoubleStream doubles() {
- return StreamSupport.doubleStream
- (new RandomDoublesSpliterator
- (0L, Long.MAX_VALUE, Double.MAX_VALUE, 0.0),
- false);
- }
-
- /**
- * Returns a stream producing the given {@code streamSize} number of
- * pseudorandom {@code double} values, each conforming to the given origin
- * (inclusive) and bound (exclusive).
- *
- * @param streamSize the number of values to generate
- * @param randomNumberOrigin the origin (inclusive) of each random value
- * @param randomNumberBound the bound (exclusive) of each random value
- * @return a stream of pseudorandom {@code double} values,
- * each with the given origin (inclusive) and bound (exclusive)
- * @throws IllegalArgumentException if {@code streamSize} is
- * less than zero, or {@code randomNumberOrigin}
- * is greater than or equal to {@code randomNumberBound}
- * @since 1.8
- */
- public DoubleStream doubles(long streamSize, double randomNumberOrigin,
- double randomNumberBound) {
- if (streamSize < 0L)
- throw new IllegalArgumentException(BAD_SIZE);
- if (!(randomNumberOrigin < randomNumberBound))
- throw new IllegalArgumentException(BAD_RANGE);
- return StreamSupport.doubleStream
- (new RandomDoublesSpliterator
- (0L, streamSize, randomNumberOrigin, randomNumberBound),
- false);
- }
-
- /**
- * Returns an effectively unlimited stream of pseudorandom {@code
- * double} values, each conforming to the given origin (inclusive) and bound
- * (exclusive).
- *
- * @implNote This method is implemented to be equivalent to {@code
- * doubles(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
- *
- * @param randomNumberOrigin the origin (inclusive) of each random value
- * @param randomNumberBound the bound (exclusive) of each random value
- * @return a stream of pseudorandom {@code double} values,
- * each with the given origin (inclusive) and bound (exclusive)
- * @throws IllegalArgumentException if {@code randomNumberOrigin}
- * is greater than or equal to {@code randomNumberBound}
- * @since 1.8
- */
- public DoubleStream doubles(double randomNumberOrigin, double randomNumberBound) {
- if (!(randomNumberOrigin < randomNumberBound))
- throw new IllegalArgumentException(BAD_RANGE);
- return StreamSupport.doubleStream
- (new RandomDoublesSpliterator
- (0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
- false);
- }
-
- /**
- * Spliterator for int streams. We multiplex the four int
- * versions into one class by treating a bound less than origin as
- * unbounded, and also by treating "infinite" as equivalent to
- * Long.MAX_VALUE. For splits, it uses the standard divide-by-two
- * approach. The long and double versions of this class are
- * identical except for types.
- */
- private static final class RandomIntsSpliterator
- implements Spliterator.OfInt {
- long index;
- final long fence;
- final int origin;
- final int bound;
- RandomIntsSpliterator(long index, long fence,
- int origin, int bound) {
- this.index = index; this.fence = fence;
- this.origin = origin; this.bound = bound;
- }
-
- public RandomIntsSpliterator trySplit() {
- long i = index, m = (i + fence) >>> 1;
- return (m <= i) ? null :
- new RandomIntsSpliterator(i, index = m, origin, bound);
- }
-
- public long estimateSize() {
- return fence - index;
- }
-
- public int characteristics() {
- return (Spliterator.SIZED | Spliterator.SUBSIZED |
- Spliterator.NONNULL | Spliterator.IMMUTABLE);
- }
-
- public boolean tryAdvance(IntConsumer consumer) {
- if (consumer == null) throw new NullPointerException();
- long i = index, f = fence;
- if (i < f) {
- consumer.accept(ThreadLocalRandom.current().internalNextInt(origin, bound));
- index = i + 1;
- return true;
- }
- return false;
- }
-
- public void forEachRemaining(IntConsumer consumer) {
- if (consumer == null) throw new NullPointerException();
- long i = index, f = fence;
- if (i < f) {
- index = f;
- int o = origin, b = bound;
- ThreadLocalRandom rng = ThreadLocalRandom.current();
- do {
- consumer.accept(rng.internalNextInt(o, b));
- } while (++i < f);
- }
- }
- }
-
- /**
- * Spliterator for long streams.
- */
- private static final class RandomLongsSpliterator
- implements Spliterator.OfLong {
- long index;
- final long fence;
- final long origin;
- final long bound;
- RandomLongsSpliterator(long index, long fence,
- long origin, long bound) {
- this.index = index; this.fence = fence;
- this.origin = origin; this.bound = bound;
- }
-
- public RandomLongsSpliterator trySplit() {
- long i = index, m = (i + fence) >>> 1;
- return (m <= i) ? null :
- new RandomLongsSpliterator(i, index = m, origin, bound);
- }
-
- public long estimateSize() {
- return fence - index;
- }
-
- public int characteristics() {
- return (Spliterator.SIZED | Spliterator.SUBSIZED |
- Spliterator.NONNULL | Spliterator.IMMUTABLE);
- }
-
- public boolean tryAdvance(LongConsumer consumer) {
- if (consumer == null) throw new NullPointerException();
- long i = index, f = fence;
- if (i < f) {
- consumer.accept(ThreadLocalRandom.current().internalNextLong(origin, bound));
- index = i + 1;
- return true;
- }
- return false;
- }
-
- public void forEachRemaining(LongConsumer consumer) {
- if (consumer == null) throw new NullPointerException();
- long i = index, f = fence;
- if (i < f) {
- index = f;
- long o = origin, b = bound;
- ThreadLocalRandom rng = ThreadLocalRandom.current();
- do {
- consumer.accept(rng.internalNextLong(o, b));
- } while (++i < f);
- }
- }
-
- }
-
- /**
- * Spliterator for double streams.
- */
- private static final class RandomDoublesSpliterator
- implements Spliterator.OfDouble {
- long index;
- final long fence;
- final double origin;
- final double bound;
- RandomDoublesSpliterator(long index, long fence,
- double origin, double bound) {
- this.index = index; this.fence = fence;
- this.origin = origin; this.bound = bound;
- }
-
- public RandomDoublesSpliterator trySplit() {
- long i = index, m = (i + fence) >>> 1;
- return (m <= i) ? null :
- new RandomDoublesSpliterator(i, index = m, origin, bound);
- }
-
- public long estimateSize() {
- return fence - index;
- }
-
- public int characteristics() {
- return (Spliterator.SIZED | Spliterator.SUBSIZED |
- Spliterator.NONNULL | Spliterator.IMMUTABLE);
- }
-
- public boolean tryAdvance(DoubleConsumer consumer) {
- if (consumer == null) throw new NullPointerException();
- long i = index, f = fence;
- if (i < f) {
- consumer.accept(ThreadLocalRandom.current().internalNextDouble(origin, bound));
- index = i + 1;
- return true;
- }
- return false;
- }
-
- public void forEachRemaining(DoubleConsumer consumer) {
- if (consumer == null) throw new NullPointerException();
- long i = index, f = fence;
- if (i < f) {
- index = f;
- double o = origin, b = bound;
- ThreadLocalRandom rng = ThreadLocalRandom.current();
- do {
- consumer.accept(rng.internalNextDouble(o, b));
- } while (++i < f);
- }
- }
- }
-
-
// Within-package utilities
/*
@@ -1039,13 +345,6 @@
*/
private static final long SEEDER_INCREMENT = 0xbb67ae8584caa73bL;
- /**
- * The least non-zero value returned by nextDouble(). This value
- * is scaled by a random value of 53 bits to produce a result.
- */
- 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)
-
// IllegalArgumentException messages
static final String BAD_BOUND = "bound must be positive";
static final String BAD_RANGE = "bound must be greater than origin";
@@ -1066,10 +365,6 @@
private static final long INHERITEDACCESSCONTROLCONTEXT = U.objectFieldOffset
(Thread.class, "inheritedAccessControlContext");
- /** Rarely-used holder for the second of a pair of Gaussians */
- private static final ThreadLocal {@code
- * public int nextInt(int bound) {
- * if (bound <= 0)
- * throw new IllegalArgumentException("bound must be positive");
- *
- * if ((bound & -bound) == bound) // i.e., bound is a power of 2
- * return (int)((bound * (long)next(31)) >> 31);
- *
- * int bits, val;
- * do {
- * bits = next(31);
- * val = bits % bound;
- * } while (bits - val + (bound-1) < 0);
- * return val;
- * }}
- *
- * {@code
- * int nextInt(int origin, int bound) {
- * int n = bound - origin;
- * if (n > 0) {
- * return nextInt(n) + origin;
- * }
- * else { // range not representable as int
- * int r;
- * do {
- * r = nextInt();
- * } while (r < origin || r >= bound);
- * return r;
- * }
- * }}
- *
- * @param streamSize the number of values to generate
- * @param randomNumberOrigin the origin (inclusive) of each random value
- * @param randomNumberBound the bound (exclusive) of each random value
- * @return a stream of pseudorandom {@code int} values,
- * each with the given origin (inclusive) and bound (exclusive)
- * @throws IllegalArgumentException if {@code streamSize} is
- * less than zero, or {@code randomNumberOrigin}
- * is greater than or equal to {@code randomNumberBound}
- * @since 1.8
- */
- public IntStream ints(long streamSize, int randomNumberOrigin,
- int randomNumberBound) {
- if (streamSize < 0L)
- throw new IllegalArgumentException(BadSize);
- if (randomNumberOrigin >= randomNumberBound)
- throw new IllegalArgumentException(BadRange);
- return StreamSupport.intStream
- (new RandomIntsSpliterator
- (this, 0L, streamSize, randomNumberOrigin, randomNumberBound),
- false);
- }
-
- /**
- * Returns an effectively unlimited stream of pseudorandom {@code
- * int} values, each conforming to the given origin (inclusive) and bound
- * (exclusive).
- *
- * {@code
- * int nextInt(int origin, int bound) {
- * int n = bound - origin;
- * if (n > 0) {
- * return nextInt(n) + origin;
- * }
- * else { // range not representable as int
- * int r;
- * do {
- * r = nextInt();
- * } while (r < origin || r >= bound);
- * return r;
- * }
- * }}
- *
- * @implNote This method is implemented to be equivalent to {@code
- * ints(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
- *
- * @param randomNumberOrigin the origin (inclusive) of each random value
- * @param randomNumberBound the bound (exclusive) of each random value
- * @return a stream of pseudorandom {@code int} values,
- * each with the given origin (inclusive) and bound (exclusive)
- * @throws IllegalArgumentException if {@code randomNumberOrigin}
- * is greater than or equal to {@code randomNumberBound}
- * @since 1.8
- */
- public IntStream ints(int randomNumberOrigin, int randomNumberBound) {
- if (randomNumberOrigin >= randomNumberBound)
- throw new IllegalArgumentException(BadRange);
- return StreamSupport.intStream
- (new RandomIntsSpliterator
- (this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
- false);
- }
-
- /**
- * Returns a stream producing the given {@code streamSize} number of
- * pseudorandom {@code long} values.
- *
- * {@code
- * long nextLong(long origin, long bound) {
- * long r = nextLong();
- * long n = bound - origin, m = n - 1;
- * if ((n & m) == 0L) // power of two
- * r = (r & m) + origin;
- * else if (n > 0L) { // reject over-represented candidates
- * for (long u = r >>> 1; // ensure nonnegative
- * u + m - (r = u % n) < 0L; // rejection check
- * u = nextLong() >>> 1) // retry
- * ;
- * r += origin;
- * }
- * else { // range not representable as long
- * while (r < origin || r >= bound)
- * r = nextLong();
- * }
- * return r;
- * }}
- *
- * @param streamSize the number of values to generate
- * @param randomNumberOrigin the origin (inclusive) of each random value
- * @param randomNumberBound the bound (exclusive) of each random value
- * @return a stream of pseudorandom {@code long} values,
- * each with the given origin (inclusive) and bound (exclusive)
- * @throws IllegalArgumentException if {@code streamSize} is
- * less than zero, or {@code randomNumberOrigin}
- * is greater than or equal to {@code randomNumberBound}
- * @since 1.8
- */
- public LongStream longs(long streamSize, long randomNumberOrigin,
- long randomNumberBound) {
- if (streamSize < 0L)
- throw new IllegalArgumentException(BadSize);
- if (randomNumberOrigin >= randomNumberBound)
- throw new IllegalArgumentException(BadRange);
- return StreamSupport.longStream
- (new RandomLongsSpliterator
- (this, 0L, streamSize, randomNumberOrigin, randomNumberBound),
- false);
- }
-
- /**
- * Returns an effectively unlimited stream of pseudorandom {@code
- * long} values, each conforming to the given origin (inclusive) and bound
- * (exclusive).
- *
- * {@code
- * long nextLong(long origin, long bound) {
- * long r = nextLong();
- * long n = bound - origin, m = n - 1;
- * if ((n & m) == 0L) // power of two
- * r = (r & m) + origin;
- * else if (n > 0L) { // reject over-represented candidates
- * for (long u = r >>> 1; // ensure nonnegative
- * u + m - (r = u % n) < 0L; // rejection check
- * u = nextLong() >>> 1) // retry
- * ;
- * r += origin;
- * }
- * else { // range not representable as long
- * while (r < origin || r >= bound)
- * r = nextLong();
- * }
- * return r;
- * }}
- *
- * @implNote This method is implemented to be equivalent to {@code
- * longs(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
- *
- * @param randomNumberOrigin the origin (inclusive) of each random value
- * @param randomNumberBound the bound (exclusive) of each random value
- * @return a stream of pseudorandom {@code long} values,
- * each with the given origin (inclusive) and bound (exclusive)
- * @throws IllegalArgumentException if {@code randomNumberOrigin}
- * is greater than or equal to {@code randomNumberBound}
- * @since 1.8
- */
- public LongStream longs(long randomNumberOrigin, long randomNumberBound) {
- if (randomNumberOrigin >= randomNumberBound)
- throw new IllegalArgumentException(BadRange);
- return StreamSupport.longStream
- (new RandomLongsSpliterator
- (this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
- false);
- }
-
- /**
- * Returns a stream producing the given {@code streamSize} number of
- * pseudorandom {@code double} values, each between zero
- * (inclusive) and one (exclusive).
- *
- * {@code
- * double nextDouble(double origin, double bound) {
- * double r = nextDouble();
- * r = r * (bound - origin) + origin;
- * if (r >= bound) // correct for rounding
- * r = Math.nextDown(bound);
- * return r;
- * }}
- *
- * @param streamSize the number of values to generate
- * @param randomNumberOrigin the origin (inclusive) of each random value
- * @param randomNumberBound the bound (exclusive) of each random value
- * @return a stream of pseudorandom {@code double} values,
- * each with the given origin (inclusive) and bound (exclusive)
- * @throws IllegalArgumentException if {@code streamSize} is
- * less than zero
- * @throws IllegalArgumentException if {@code randomNumberOrigin}
- * is greater than or equal to {@code randomNumberBound}
- * @since 1.8
- */
- public DoubleStream doubles(long streamSize, double randomNumberOrigin,
- double randomNumberBound) {
- if (streamSize < 0L)
- throw new IllegalArgumentException(BadSize);
- if (!(randomNumberOrigin < randomNumberBound))
- throw new IllegalArgumentException(BadRange);
- return StreamSupport.doubleStream
- (new RandomDoublesSpliterator
- (this, 0L, streamSize, randomNumberOrigin, randomNumberBound),
- false);
- }
-
- /**
- * Returns an effectively unlimited stream of pseudorandom {@code
- * double} values, each conforming to the given origin (inclusive) and bound
- * (exclusive).
- *
- * {@code
- * double nextDouble(double origin, double bound) {
- * double r = nextDouble();
- * r = r * (bound - origin) + origin;
- * if (r >= bound) // correct for rounding
- * r = Math.nextDown(bound);
- * return r;
- * }}
- *
- * @implNote This method is implemented to be equivalent to {@code
- * doubles(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
- *
- * @param randomNumberOrigin the origin (inclusive) of each random value
- * @param randomNumberBound the bound (exclusive) of each random value
- * @return a stream of pseudorandom {@code double} values,
- * each with the given origin (inclusive) and bound (exclusive)
- * @throws IllegalArgumentException if {@code randomNumberOrigin}
- * is greater than or equal to {@code randomNumberBound}
- * @since 1.8
- */
- public DoubleStream doubles(double randomNumberOrigin, double randomNumberBound) {
- if (!(randomNumberOrigin < randomNumberBound))
- throw new IllegalArgumentException(BadRange);
- return StreamSupport.doubleStream
- (new RandomDoublesSpliterator
- (this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
- false);
- }
-
- /**
- * Spliterator for int streams. We multiplex the four int
- * versions into one class by treating a bound less than origin as
- * unbounded, and also by treating "infinite" as equivalent to
- * Long.MAX_VALUE. For splits, it uses the standard divide-by-two
- * approach. The long and double versions of this class are
- * identical except for types.
- */
- static final class RandomIntsSpliterator implements Spliterator.OfInt {
- final Random rng;
- long index;
- final long fence;
- final int origin;
- final int bound;
- RandomIntsSpliterator(Random rng, long index, long fence,
- int origin, int bound) {
- this.rng = rng; this.index = index; this.fence = fence;
- this.origin = origin; this.bound = bound;
- }
-
- public RandomIntsSpliterator trySplit() {
- long i = index, m = (i + fence) >>> 1;
- return (m <= i) ? null :
- new RandomIntsSpliterator(rng, i, index = m, origin, bound);
- }
-
- public long estimateSize() {
- return fence - index;
- }
-
- public int characteristics() {
- return (Spliterator.SIZED | Spliterator.SUBSIZED |
- Spliterator.NONNULL | Spliterator.IMMUTABLE);
- }
-
- public boolean tryAdvance(IntConsumer consumer) {
- if (consumer == null) throw new NullPointerException();
- long i = index, f = fence;
- if (i < f) {
- consumer.accept(rng.internalNextInt(origin, bound));
- index = i + 1;
- return true;
- }
- return false;
- }
-
- public void forEachRemaining(IntConsumer consumer) {
- if (consumer == null) throw new NullPointerException();
- long i = index, f = fence;
- if (i < f) {
- index = f;
- Random r = rng;
- int o = origin, b = bound;
- do {
- consumer.accept(r.internalNextInt(o, b));
- } while (++i < f);
- }
- }
- }
-
- /**
- * Spliterator for long streams.
- */
- static final class RandomLongsSpliterator implements Spliterator.OfLong {
- final Random rng;
- long index;
- final long fence;
- final long origin;
- final long bound;
- RandomLongsSpliterator(Random rng, long index, long fence,
- long origin, long bound) {
- this.rng = rng; this.index = index; this.fence = fence;
- this.origin = origin; this.bound = bound;
- }
-
- public RandomLongsSpliterator trySplit() {
- long i = index, m = (i + fence) >>> 1;
- return (m <= i) ? null :
- new RandomLongsSpliterator(rng, i, index = m, origin, bound);
- }
-
- public long estimateSize() {
- return fence - index;
- }
-
- public int characteristics() {
- return (Spliterator.SIZED | Spliterator.SUBSIZED |
- Spliterator.NONNULL | Spliterator.IMMUTABLE);
- }
-
- public boolean tryAdvance(LongConsumer consumer) {
- if (consumer == null) throw new NullPointerException();
- long i = index, f = fence;
- if (i < f) {
- consumer.accept(rng.internalNextLong(origin, bound));
- index = i + 1;
- return true;
- }
- return false;
- }
-
- public void forEachRemaining(LongConsumer consumer) {
- if (consumer == null) throw new NullPointerException();
- long i = index, f = fence;
- if (i < f) {
- index = f;
- Random r = rng;
- long o = origin, b = bound;
- do {
- consumer.accept(r.internalNextLong(o, b));
- } while (++i < f);
- }
- }
-
- }
-
- /**
- * Spliterator for double streams.
- */
- static final class RandomDoublesSpliterator implements Spliterator.OfDouble {
- final Random rng;
- long index;
- final long fence;
- final double origin;
- final double bound;
- RandomDoublesSpliterator(Random rng, long index, long fence,
- double origin, double bound) {
- this.rng = rng; this.index = index; this.fence = fence;
- this.origin = origin; this.bound = bound;
- }
-
- public RandomDoublesSpliterator trySplit() {
- long i = index, m = (i + fence) >>> 1;
- return (m <= i) ? null :
- new RandomDoublesSpliterator(rng, i, index = m, origin, bound);
- }
-
- public long estimateSize() {
- return fence - index;
- }
-
- public int characteristics() {
- return (Spliterator.SIZED | Spliterator.SUBSIZED |
- Spliterator.NONNULL | Spliterator.IMMUTABLE);
- }
-
- public boolean tryAdvance(DoubleConsumer consumer) {
- if (consumer == null) throw new NullPointerException();
- long i = index, f = fence;
- if (i < f) {
- consumer.accept(rng.internalNextDouble(origin, bound));
- index = i + 1;
- return true;
- }
- return false;
- }
-
- public void forEachRemaining(DoubleConsumer consumer) {
- if (consumer == null) throw new NullPointerException();
- long i = index, f = fence;
- if (i < f) {
- index = f;
- Random r = rng;
- double o = origin, b = bound;
- do {
- consumer.accept(r.internalNextDouble(o, b));
- } while (++i < f);
- }
- }
- }
-
/**
* Serializable fields for Random.
*
diff -r 0303567f1dd1 -r b1e6bc96af3d src/java.base/share/classes/java/util/Rng.java
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.base/share/classes/java/util/Rng.java Tue Jun 04 13:07:35 2019 -0400
@@ -0,0 +1,638 @@
+/*
+ * 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 rng a random number generator to be used as a
+ * source of pseudorandom {@code long} 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 rng a random number generator to be used as a
+ * source of pseudorandom {@code long} values
+ * @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 rng a random number generator to be used as a
+ * source of pseudorandom {@code int} 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 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 rng a random number generator to be used as a
+ * source of pseudorandom {@code long} values
+ * @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 rng a random number generator to be used as a
+ * source of pseudorandom {@code double} values
+ * @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 rng a random number generator to be used as a
+ * source of pseudorandom {@code double} values
+ * @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 rng a random number generator to be used as a
+ * source of pseudorandom {@code float} values
+ * @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 rng a random number generator to be used as a
+ * source of pseudorandom {@code float} values
+ * @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
+ * not be called repeatedly, once per constructed
+ * object; at most it should be called once per class.)
+ *
+ * @return a {@code long} value, randomly chosen using
+ * appropriate environmental entropy
+ */
+ public static long initialSeed() {
+ if (useSecureRandomSeed) {
+ byte[] seedBytes = java.security.SecureRandom.getSeed(8);
+ long s = (long)(seedBytes[0]) & 0xffL;
+ for (int i = 1; i < 8; ++i)
+ s = (s << 8) | ((long)(seedBytes[i]) & 0xffL);
+ return s;
+ }
+ return (mixStafford13(System.currentTimeMillis()) ^
+ mixStafford13(System.nanoTime()));
+ }
+
+ /**
+ * The first 32 bits of the golden ratio (1+sqrt(5))/2, forced to be odd.
+ * Useful for producing good Weyl sequences or as an arbitrary nonzero odd value.
+ */
+ public static final int GOLDEN_RATIO_32 = 0x9e3779b9;
+
+ /**
+ * The first 64 bits of the golden ratio (1+sqrt(5))/2, forced to be odd.
+ * Useful for producing good Weyl sequences or as an arbitrary nonzero odd value.
+ */
+ public static final long GOLDEN_RATIO_64 = 0x9e3779b97f4a7c15L;
+
+ /**
+ * The first 32 bits of the silver ratio 1+sqrt(2), forced to be odd.
+ * Useful for producing good Weyl sequences or as an arbitrary nonzero odd value.
+ */
+ public static final int SILVER_RATIO_32 = 0x6A09E667;
+
+ /**
+ * The first 64 bits of the silver ratio 1+sqrt(2), forced to be odd.
+ * Useful for producing good Weyl sequences or as an arbitrary nonzero odd value.
+ */
+ public static final long SILVER_RATIO_64 = 0x6A09E667F3BCC909L;
+
+ /**
+ * Computes the 64-bit mixing function for MurmurHash3.
+ * This is a 64-bit hashing function with excellent avalanche statistics.
+ * https://github.com/aappleby/smhasher/wiki/MurmurHash3
+ *
+ * Note that if the argument {@code z} is 0, the result is 0.
+ *
+ * @param z any long value
+ *
+ * @return the result of hashing z
+ */
+ public static long mixMurmur64(long z) {
+ z = (z ^ (z >>> 33)) * 0xff51afd7ed558ccdL;
+ z = (z ^ (z >>> 33)) * 0xc4ceb9fe1a85ec53L;
+ return z ^ (z >>> 33);
+ }
+
+ /**
+ * Computes Stafford variant 13 of the 64-bit mixing function for MurmurHash3.
+ * This is a 64-bit hashing function with excellent avalanche statistics.
+ * http://zimbry.blogspot.com/2011/09/better-bit-mixing-improving-on.html
+ *
+ * Note that if the argument {@code z} is 0, the result is 0.
+ *
+ * @param z any long value
+ *
+ * @return the result of hashing z
+ */
+ public static long mixStafford13(long z) {
+ z = (z ^ (z >>> 30)) * 0xbf58476d1ce4e5b9L;
+ z = (z ^ (z >>> 27)) * 0x94d049bb133111ebL;
+ return z ^ (z >>> 31);
+ }
+
+ /**
+ * Computes Doug Lea's 64-bit mixing function.
+ * This is a 64-bit hashing function with excellent avalanche statistics.
+ * It has the advantages of using the same multiplicative constant twice
+ * and of using only 32-bit shifts.
+ *
+ * Note that if the argument {@code z} is 0, the result is 0.
+ *
+ * @param z any long value
+ *
+ * @return the result of hashing z
+ */
+ public static long mixLea64(long z) {
+ z = (z ^ (z >>> 32)) * 0xdaba0b6eb09322e3L;
+ z = (z ^ (z >>> 32)) * 0xdaba0b6eb09322e3L;
+ return z ^ (z >>> 32);
+ }
+
+ /**
+ * Computes the 32-bit mixing function for MurmurHash3.
+ * This is a 32-bit hashing function with excellent avalanche statistics.
+ * https://github.com/aappleby/smhasher/wiki/MurmurHash3
+ *
+ * Note that if the argument {@code z} is 0, the result is 0.
+ *
+ * @param z any long value
+ *
+ * @return the result of hashing z
+ */
+ public static int mixMurmur32(int z) {
+ z = (z ^ (z >>> 16)) * 0x85ebca6b;
+ z = (z ^ (z >>> 13)) * 0xc2b2ae35;
+ return z ^ (z >>> 16);
+ }
+
+ /**
+ * Computes Doug Lea's 32-bit mixing function.
+ * This is a 32-bit hashing function with excellent avalanche statistics.
+ * It has the advantages of using the same multiplicative constant twice
+ * and of using only 16-bit shifts.
+ *
+ * Note that if the argument {@code z} is 0, the result is 0.
+ *
+ * @param z any long value
+ *
+ * @return the result of hashing z
+ */
+ public static int mixLea32(int z) {
+ z = (z ^ (z >>> 16)) * 0xd36d884b;
+ z = (z ^ (z >>> 16)) * 0xd36d884b;
+ return z ^ (z >>> 16);
+ }
+
+ // Non-public (package only) support for spliterators needed by AbstractSplittableRng
+ // and AbstractArbitrarilyJumpableRng and AbstractSharedRng
+
+ /**
+ * Base class for making Spliterator classes for streams of randomly chosen values.
+ */
+ static abstract class RandomSpliterator {
+ long index;
+ final long fence;
+
+ RandomSpliterator(long index, long fence) {
+ this.index = index; this.fence = fence;
+ }
+
+ public long estimateSize() {
+ return fence - index;
+ }
+
+ public int characteristics() {
+ return (Spliterator.SIZED | Spliterator.SUBSIZED |
+ Spliterator.NONNULL | Spliterator.IMMUTABLE);
+ }
+ }
+
+
+ /*
+ * Implementation support for nextExponential() and nextGaussian() methods of Rng.
+ *
+ * Each is implemented using McFarland's fast modified ziggurat algorithm (largely
+ * table-driven, with rare cases handled by computation and rejection sampling).
+ * Walker's alias method for sampling a discrete distribution also plays a role.
+ *
+ * The tables themselves, as well as a number of associated parameters, are defined
+ * in class java.util.DoubleZigguratTables, which is automatically generated by the
+ * program create_ziggurat_tables.c (which takes only a few seconds to run).
+ *
+ * For more information about the algorithms, see these articles:
+ *
+ * Christopher D. McFarland. 2016 (published online 24 Jun 2015). A modified ziggurat
+ * algorithm for generating exponentially and normally distributed pseudorandom numbers.
+ * Journal of Statistical Computation and Simulation 86 (7), pages 1281-1294.
+ * https://www.tandfonline.com/doi/abs/10.1080/00949655.2015.1060234
+ * Also at https://arxiv.org/abs/1403.6870 (26 March 2014).
+ *
+ * Alastair J. Walker. 1977. An efficient method for generating discrete random
+ * variables with general distributions. ACM Trans. Math. Software 3, 3
+ * (September 1977), 253-256. DOI: https://doi.org/10.1145/355744.355749
+ *
+ * Certain details of these algorithms depend critically on the quality of the
+ * low-order bits delivered by NextLong(). These algorithms should not be used
+ * with RNG algorithms (such as a simple Linear Congruential Generator) whose
+ * low-order output bits do not have good statistical quality.
+ */
+
+ // Implementation support for nextExponential()
+
+ static double computeNextExponential(Rng rng) {
+ long U1 = rng.nextLong();
+ // Experimentation on a variety of machines indicates that it is overall much faster
+ // to do the following & and < operations on longs rather than first cast U1 to int
+ // (but then we need to cast to int before doing the array indexing operation).
+ long i = U1 & DoubleZigguratTables.exponentialLayerMask;
+ if (i < DoubleZigguratTables.exponentialNumberOfLayers) {
+ // This is the fast path (occurring more than 98% of the time). Make an early exit.
+ return DoubleZigguratTables.exponentialX[(int)i] * (U1 >>> 1);
+ }
+ // We didn't use the upper part of U1 after all. We'll be able to use it later.
+
+ for (double extra = 0.0; ; ) {
+ // Use Walker's alias method to sample an (unsigned) integer j from a discrete
+ // probability distribution that includes the tail and all the ziggurat overhangs;
+ // j will be less than DoubleZigguratTables.exponentialNumberOfLayers + 1.
+ long UA = rng.nextLong();
+ int j = (int)UA & DoubleZigguratTables.exponentialAliasMask;
+ if (UA >= DoubleZigguratTables.exponentialAliasThreshold[j]) {
+ j = DoubleZigguratTables.exponentialAliasMap[j] & DoubleZigguratTables.exponentialSignCorrectionMask;
+ }
+ if (j > 0) { // Sample overhang j
+ // For the exponential distribution, every overhang is convex.
+ final double[] X = DoubleZigguratTables.exponentialX;
+ final double[] Y = DoubleZigguratTables.exponentialY;
+ for (;; U1 = (rng.nextLong() >>> 1)) {
+ long U2 = (rng.nextLong() >>> 1);
+ // Compute the actual x-coordinate of the randomly chosen point.
+ double x = (X[j] * 0x1.0p63) + ((X[j-1] - X[j]) * (double)U1);
+ // Does the point lie below the curve?
+ long Udiff = U2 - U1;
+ if (Udiff < 0) {
+ // We picked a point in the upper-right triangle. None of those can be accepted.
+ // So remap the point into the lower-left triangle and try that.
+ // In effect, we swap U1 and U2, and invert the sign of Udiff.
+ Udiff = -Udiff;
+ U2 = U1;
+ U1 -= Udiff;
+ }
+ if (Udiff >= DoubleZigguratTables.exponentialConvexMargin) {
+ return x + extra; // The chosen point is way below the curve; accept it.
+ }
+ // Compute the actual y-coordinate of the randomly chosen point.
+ double y = (Y[j] * 0x1.0p63) + ((Y[j] - Y[j-1]) * (double)U2);
+ // Now see how that y-coordinate compares to the curve
+ if (y <= Math.exp(-x)) {
+ return x + extra; // The chosen point is below the curve; accept it.
+ }
+ // Otherwise, we reject this sample and have to try again.
+ }
+ }
+ // We are now committed to sampling from the tail. We could do a recursive call
+ // and then add X[0] but we save some time and stack space by using an iterative loop.
+ extra += DoubleZigguratTables.exponentialX0;
+ // This is like the first five lines of this method, but if it returns, it first adds "extra".
+ U1 = rng.nextLong();
+ i = U1 & DoubleZigguratTables.exponentialLayerMask;
+ if (i < DoubleZigguratTables.exponentialNumberOfLayers) {
+ return DoubleZigguratTables.exponentialX[(int)i] * (U1 >>> 1) + extra;
+ }
+ }
+ }
+
+ // Implementation support for nextGaussian()
+
+ static double computeNextGaussian(Rng rng) {
+ long U1 = rng.nextLong();
+ // Experimentation on a variety of machines indicates that it is overall much faster
+ // to do the following & and < operations on longs rather than first cast U1 to int
+ // (but then we need to cast to int before doing the array indexing operation).
+ long i = U1 & DoubleZigguratTables.normalLayerMask;
+
+ if (i < DoubleZigguratTables.normalNumberOfLayers) {
+ // This is the fast path (occurring more than 98% of the time). Make an early exit.
+ return DoubleZigguratTables.normalX[(int)i] * U1; // Note that the sign bit of U1 is used here.
+ }
+ // We didn't use the upper part of U1 after all.
+ // Pull U1 apart into a sign bit and a 63-bit value for later use.
+ double signBit = (U1 >= 0) ? 1.0 : -1.0;
+ U1 = (U1 << 1) >>> 1;
+
+ // Use Walker's alias method to sample an (unsigned) integer j from a discrete
+ // probability distribution that includes the tail and all the ziggurat overhangs;
+ // j will be less than DoubleZigguratTables.normalNumberOfLayers + 1.
+ long UA = rng.nextLong();
+ int j = (int)UA & DoubleZigguratTables.normalAliasMask;
+ if (UA >= DoubleZigguratTables.normalAliasThreshold[j]) {
+ j = DoubleZigguratTables.normalAliasMap[j] & DoubleZigguratTables.normalSignCorrectionMask;
+ }
+
+ double x;
+ // Now the goal is to choose the result, which will be multiplied by signBit just before return.
+
+ // There are four kinds of overhangs:
+ //
+ // j == 0 : Sample from tail
+ // 0 < j < normalInflectionIndex : Overhang is convex; can reject upper-right triangle
+ // j == normalInflectionIndex : Overhang includes the inflection point
+ // j > normalInflectionIndex : Overhang is concave; can accept point in lower-left triangle
+ //
+ // Choose one of four loops to compute x, each specialized for a specific kind of overhang.
+ // Conditional statements are arranged such that the more likely outcomes are first.
+
+ // In the three cases other than the tail case:
+ // U1 represents a fraction (scaled by 2**63) of the width of rectangle measured from the left.
+ // U2 represents a fraction (scaled by 2**63) of the height of rectangle measured from the top.
+ // Together they indicate a randomly chosen point within the rectangle.
+
+ final double[] X = DoubleZigguratTables.normalX;
+ final double[] Y = DoubleZigguratTables.normalY;
+ if (j > DoubleZigguratTables.normalInflectionIndex) { // Concave overhang
+ for (;; U1 = (rng.nextLong() >>> 1)) {
+ long U2 = (rng.nextLong() >>> 1);
+ // Compute the actual x-coordinate of the randomly chosen point.
+ x = (X[j] * 0x1.0p63) + ((X[j-1] - X[j]) * (double)U1);
+ // Does the point lie below the curve?
+ long Udiff = U2 - U1;
+ if (Udiff >= 0) {
+ break; // The chosen point is in the lower-left triangle; accept it.
+ }
+ if (Udiff <= -DoubleZigguratTables.normalConcaveMargin) {
+ continue; // The chosen point is way above the curve; reject it.
+ }
+ // Compute the actual y-coordinate of the randomly chosen point.
+ double y = (Y[j] * 0x1.0p63) + ((Y[j] - Y[j-1]) * (double)U2);
+ // Now see how that y-coordinate compares to the curve
+ if (y <= Math.exp(-0.5*x*x)) {
+ break; // The chosen point is below the curve; accept it.
+ }
+ // Otherwise, we reject this sample and have to try again.
+ }
+ } else if (j == 0) { // Tail
+ // Tail-sampling method of Marsaglia and Tsang. See any one of:
+ // Marsaglia and Tsang. 1984. A fast, easily implemented method for sampling from decreasing
+ // or symmetric unimodal density functions. SIAM J. Sci. Stat. Comput. 5, 349-359.
+ // Marsaglia and Tsang. 1998. The Monty Python method for generating random variables.
+ // ACM Trans. Math. Softw. 24, 3 (September 1998), 341-350. See page 342, step (4).
+ // http://doi.org/10.1145/292395.292453
+ // Thomas, Luk, Leong, and Villasenor. 2007. Gaussian random number generators.
+ // ACM Comput. Surv. 39, 4, Article 11 (November 2007). See Algorithm 16.
+ // http://doi.org/10.1145/1287620.1287622
+ // Compute two separate random exponential samples and then compare them in certain way.
+ do {
+ x = (1.0 / DoubleZigguratTables.normalX0) * computeNextExponential(rng);
+ } while (computeNextExponential(rng) < 0.5*x*x);
+ x += DoubleZigguratTables.normalX0;
+ } else if (j < DoubleZigguratTables.normalInflectionIndex) { // Convex overhang
+ for (;; U1 = (rng.nextLong() >>> 1)) {
+ long U2 = (rng.nextLong() >>> 1);
+ // Compute the actual x-coordinate of the randomly chosen point.
+ x = (X[j] * 0x1.0p63) + ((X[j-1] - X[j]) * (double)U1);
+ // Does the point lie below the curve?
+ long Udiff = U2 - U1;
+ if (Udiff < 0) {
+ // We picked a point in the upper-right triangle. None of those can be accepted.
+ // So remap the point into the lower-left triangle and try that.
+ // In effect, we swap U1 and U2, and invert the sign of Udiff.
+ Udiff = -Udiff;
+ U2 = U1;
+ U1 -= Udiff;
+ }
+ if (Udiff >= DoubleZigguratTables.normalConvexMargin) {
+ break; // The chosen point is way below the curve; accept it.
+ }
+ // Compute the actual y-coordinate of the randomly chosen point.
+ double y = (Y[j] * 0x1.0p63) + ((Y[j] - Y[j-1]) * (double)U2);
+ // Now see how that y-coordinate compares to the curve
+ if (y <= Math.exp(-0.5*x*x)) break; // The chosen point is below the curve; accept it.
+ // Otherwise, we reject this sample and have to try again.
+ }
+ } else {
+ // The overhang includes the inflection point, so the curve is both convex and concave
+ for (;; U1 = (rng.nextLong() >>> 1)) {
+ long U2 = (rng.nextLong() >>> 1);
+ // Compute the actual x-coordinate of the randomly chosen point.
+ x = (X[j] * 0x1.0p63) + ((X[j-1] - X[j]) * (double)U1);
+ // Does the point lie below the curve?
+ long Udiff = U2 - U1;
+ if (Udiff >= DoubleZigguratTables.normalConvexMargin) {
+ break; // The chosen point is way below the curve; accept it.
+ }
+ if (Udiff <= -DoubleZigguratTables.normalConcaveMargin) {
+ continue; // The chosen point is way above the curve; reject it.
+ }
+ // Compute the actual y-coordinate of the randomly chosen point.
+ double y = (Y[j] * 0x1.0p63) + ((Y[j] - Y[j-1]) * (double)U2);
+ // Now see how that y-coordinate compares to the curve
+ if (y <= Math.exp(-0.5*x*x)) {
+ break; // The chosen point is below the curve; accept it.
+ }
+ // Otherwise, we reject this sample and have to try again.
+ }
+ }
+ return signBit*x;
+ }
+
+}
+
diff -r 0303567f1dd1 -r b1e6bc96af3d src/java.base/share/classes/java/util/SplittableRandom.java
--- a/src/java.base/share/classes/java/util/SplittableRandom.java Tue Jun 04 12:57:31 2019 -0400
+++ b/src/java.base/share/classes/java/util/SplittableRandom.java Tue Jun 04 13:07:35 2019 -0400
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -22,17 +22,10 @@
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
-
package java.util;
+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;
/**
* A generator of uniform pseudorandom values applicable for use in
@@ -52,15 +45,15 @@
* types and ranges, but similar properties are expected to hold, at
* least approximately, for others as well. The period
* (length of any series of generated values before it repeats) is at
- * least 264.
+ * least 264.
*
- *