Rename Rng.java to RandomNumberGenerator.java, clean up javadoc and misc code changes
--- a/src/java.base/share/classes/java/security/SecureRandom.java Thu Jun 27 18:02:51 2019 -0300
+++ b/src/java.base/share/classes/java/security/SecureRandom.java Thu Jun 27 18:30:27 2019 -0300
@@ -25,11 +25,11 @@
package java.security;
+import java.math.BigInteger;
import java.util.*;
+import java.util.random.RandomNumberGenerator;
import java.util.regex.*;
-
import java.security.Provider.Service;
-
import sun.security.jca.*;
import sun.security.jca.GetInstance.Instance;
import sun.security.util.Debug;
@@ -1023,6 +1023,16 @@
}
}
+ /**
+ * Returns the period of this random number generator.
+ *
+ * @return the period of this random number generator.
+ */
+ @Override
+ public BigInteger period() {
+ return RandomNumberGenerator.HUGE_PERIOD;
+ }
+
// Declare serialVersionUID to be compatible with JDK1.1
static final long serialVersionUID = 4940670005562187L;
--- a/src/java.base/share/classes/java/util/Random.java Thu Jun 27 18:02:51 2019 -0300
+++ b/src/java.base/share/classes/java/util/Random.java Thu Jun 27 18:30:27 2019 -0300
@@ -1,42 +1,42 @@
/*
- * Copyright (c) 1995, 2013, 2019, Oracle and/or its affiliates. All rights reserved.
- * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
- *
- *
+ * Copyright (c) 1995, 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 jdk.internal.misc.Unsafe;
+
import java.io.*;
import java.math.BigInteger;
+import java.util.Objects;
+import java.util.ServiceLoader;
+import java.util.ServiceLoader.Provider;
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 java.util.function.Function;
+import java.util.random.AbstractSharedRNG;
+import java.util.random.RandomNumberGenerator;
+import java.util.stream.Collectors;
/**
* An instance of this class is used to generate a stream of
@@ -76,7 +76,7 @@
* @since 1.0
*/
public
-class Random extends AbstractSharedRng 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;
@@ -207,7 +207,10 @@
return (int)(nextseed >>> (48 - bits));
}
- static final BigInteger thePeriod = BigInteger.valueOf(1L<<48); // Period is 2**48
+ /*
+ * Period of Random is 2**48
+ */
+ private static final BigInteger PERIOD = BigInteger.valueOf(1L<<48);
/**
* Returns the period of this random number generator.
@@ -215,11 +218,7 @@
* @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;
+ return PERIOD;
}
/**
@@ -496,6 +495,47 @@
}
/**
+ * Creates a new random number generator that uses the random number generator algorithm
+ * specified by name. The seed of the random number generator to a value very likely to be
+ * distinct from any other invocation.
+ *
+ * @param name name of random number generator algorithm to use.
+ *
+ * @return an instance of random number generator.
+ *
+ * @throws IllegalArgumentException if {@code name} is an unknown random number generator
+ *
+ * @since 14
+ */
+ public static RandomNumberGenerator byName(String name) throws IllegalArgumentException {
+ Objects.requireNonNull(name);
+ Map<String, Provider<RandomNumberGenerator>> rngs = getRNGMap();
+ Provider<RandomNumberGenerator> provider = rngs.get(name.toUpperCase());
+ if (provider == null) {
+ throw new IllegalArgumentException(name + " is an unknown random number generator");
+ }
+ return provider.get();
+ }
+
+ private static Map<String, Provider<RandomNumberGenerator>> rngMap;
+
+ private static Map<String, Provider<RandomNumberGenerator>> getRNGMap() {
+ if (rngMap == null) {
+ synchronized (Random.class) {
+ if (rngMap == null) {
+ rngMap = ServiceLoader
+ .load(RandomNumberGenerator.class)
+ .stream()
+ .filter(p -> !p.type().isInterface())
+ .collect(Collectors.toMap(p -> p.type().getSimpleName().toUpperCase(),
+ Function.identity()));
+ }
+ }
+ }
+ return rngMap;
+ }
+
+ /**
* Serializable fields for Random.
*
* @serialField seed long
--- a/src/java.base/share/classes/java/util/Rng.java Thu Jun 27 18:02:51 2019 -0300
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,638 +0,0 @@
-/*
- * 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.
- *
- * <p>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.
- *
- * <p>In the case of {@code int}, {@code long}, and {@code Boolean}
- * values, if there is no explicit specification of range, then the
- * range includes all possible values of the type. In the case of
- * {@code float} and {@code double} values, a value is always chosen
- * from the set of 2<sup><i>w</i></sup> values between 0.0 (inclusive)
- * and 1.0 (exclusive), where <i>w</i> is 23 for {@code float}
- * values and 52 for {@code double} values, such that adjacent values
- * differ by 2<sup>−<i>w</i></sup>; 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.
- *
- * <p>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.
- *
- * <p>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
- * <i>period</i>. (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.)
- *
- * <p>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}.
- *
- * <p>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.
- *
- * <p>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);
-}
--- a/src/java.base/share/classes/java/util/SplittableRandom.java Thu Jun 27 18:02:51 2019 -0300
+++ b/src/java.base/share/classes/java/util/SplittableRandom.java Thu Jun 27 18:30:27 2019 -0300
@@ -26,6 +26,9 @@
import java.math.BigInteger;
import java.util.concurrent.atomic.AtomicLong;
+import java.util.random.AbstractSplittableRNG;
+import java.util.random.RNGSupport;
+import java.util.random.SplittableRNG;
/**
* A generator of uniform pseudorandom values applicable for use in
@@ -79,7 +82,7 @@
* @author Doug Lea
* @since 1.8
*/
-public final class SplittableRandom extends AbstractSplittableRng {
+public final class SplittableRandom extends AbstractSplittableRNG {
/*
* Implementation Overview.
@@ -193,7 +196,7 @@
/**
* Returns the gamma value to use for a new split instance.
* Uses the 64bit mix function from MurmurHash3.
- * https://github.com/aappleby/smhasher/wiki/MurmurHash3
+ * https://github.com/aappleby/smhasher/wiki/MurmurHash3
*/
private static long mixGamma(long z) {
z = (z ^ (z >>> 33)) * 0xff51afd7ed558ccdL; // MurmurHash3 mix constants
@@ -213,8 +216,8 @@
/**
* The seed generator for default constructors.
*/
- private static final AtomicLong defaultGen = new AtomicLong(RngSupport.initialSeed());
-
+ private static final AtomicLong defaultGen = new AtomicLong(RNGSupport.initialSeed());
+
/* ---------------- public methods ---------------- */
/**
@@ -241,7 +244,7 @@
}
// public SplittableRandom copy() { return new SplittableRandom(seed, gamma); }
-
+
/**
* Constructs and returns a new SplittableRandom instance that
* shares no mutable state with this instance. However, with very
@@ -260,7 +263,7 @@
return new SplittableRandom(nextLong(), mixGamma(nextSeed()));
}
- public SplittableRandom split(SplittableRng source) {
+ public SplittableRandom split(SplittableRNG source) {
return new SplittableRandom(source.nextLong(), mixGamma(source.nextLong()));
}
--- a/src/java.base/share/classes/java/util/concurrent/ThreadLocalRandom.java Thu Jun 27 18:02:51 2019 -0300
+++ b/src/java.base/share/classes/java/util/concurrent/ThreadLocalRandom.java Thu Jun 27 18:30:27 2019 -0300
@@ -33,7 +33,7 @@
* 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.
+ * and to implement the {@link RandomNumberGenerator} interface.
*/
package java.util.concurrent;
@@ -41,10 +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.random.RNGSupport;
import jdk.internal.misc.Unsafe;
import jdk.internal.misc.VM;
@@ -123,7 +123,7 @@
* 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.
+ * default for the RandomNumberGenerator interface.
*/
private static int mix32(long z) {
@@ -152,7 +152,7 @@
static final void localInit() {
int p = probeGenerator.addAndGet(PROBE_INCREMENT);
int probe = (p == 0) ? 1 : p; // skip 0
- long seed = RngSupport.mixMurmur64(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);
@@ -216,7 +216,7 @@
* @return a pseudorandom {@code long} value
*/
public long nextLong() {
- return RngSupport.mixMurmur64(nextSeed());
+ return RNGSupport.mixMurmur64(nextSeed());
}
// Within-package utilities
@@ -375,8 +375,8 @@
* The next seed for default constructors.
*/
private static final AtomicLong seeder
- = new AtomicLong(RngSupport.mixMurmur64(System.currentTimeMillis()) ^
- RngSupport.mixMurmur64(System.nanoTime()));
+ = new AtomicLong(RNGSupport.mixMurmur64(System.currentTimeMillis()) ^
+ RNGSupport.mixMurmur64(System.nanoTime()));
// at end of <clinit> to survive static initialization circularity
static {
--- a/src/java.base/share/classes/java/util/random/AbstractArbitrarilyJumpableRNG.java Thu Jun 27 18:02:51 2019 -0300
+++ b/src/java.base/share/classes/java/util/random/AbstractArbitrarilyJumpableRNG.java Thu Jun 27 18:30:27 2019 -0300
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013, 2019, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 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,19 +22,20 @@
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
-package java.util;
+
+package java.util.random;
import java.util.Spliterator;
import java.util.function.Consumer;
+import java.util.function.DoubleConsumer;
import java.util.function.IntConsumer;
import java.util.function.LongConsumer;
-import java.util.function.DoubleConsumer;
+import java.util.stream.Stream;
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
+ * {@link ArbitrarilyJumpableRNG} interface, to minimize the effort
* required to implement that interface.
*
* To implement a pseudorandom number generator, the programmer needs
@@ -45,7 +46,7 @@
*
* (If the pseudorandom number generator also has the ability to split,
* then the programmer may wish to consider instead extending
- * {@code AbstractSplittableArbitrarilyJumpableRng}.)
+ * {@link AbstractSplittableRNG}.)
*
* The programmer should generally provide at least three constructors:
* one that takes no arguments, one that accepts a {@code long}
@@ -55,13 +56,13 @@
* 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
+ * this class provides {@link Spliterator}-based implementations that
* allow parallel execution when appropriate. In this respect
- * {@code ArbitrarilyJumpableRng} differs from {@code JumpableRng},
+ * {@link ArbitrarilyJumpableRNG} differs from {@link JumpableRNG},
* which provides very simple implementations that produce
* sequential streams only.
*
- * <p>An implementation of the {@code AbstractArbitrarilyJumpableRng} class
+ * <p>An implementation of the {@link 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()}.
@@ -72,49 +73,48 @@
* be overridden if the pseudorandom number generator being
* implemented admits a more efficient implementation.
*
- * @author Guy Steele
- * @since 1.9
+ * @since 14
*/
-public abstract class AbstractArbitrarilyJumpableRng
- extends AbstractSpliteratorRng implements ArbitrarilyJumpableRng {
+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
+ * the interface 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
+ * 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
+ // Methods required by class AbstractSpliteratorRNG
Spliterator.OfInt makeIntsSpliterator(long index, long fence, int origin, int bound) {
- return new RandomIntsSpliterator(this, index, fence, origin, 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);
+ 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);
+ return new RandomDoublesSpliterator(this, index, fence, origin, bound);
}
// Similar methods used by this class
- Spliterator<Rng> makeJumpsSpliterator(long index, long fence, double distance) {
- return new RandomJumpsSpliterator(this, index, fence, distance);
+ Spliterator<RandomNumberGenerator> makeJumpsSpliterator(long index, long fence, double distance) {
+ return new RandomJumpsSpliterator(this, index, fence, distance);
}
- Spliterator<JumpableRng> makeLeapsSpliterator(long index, long fence, double distance) {
- return new RandomLeapsSpliterator(this, index, fence, distance);
+ Spliterator<JumpableRNG> makeLeapsSpliterator(long index, long fence, double distance) {
+ return new RandomLeapsSpliterator(this, index, fence, distance);
}
- Spliterator<ArbitrarilyJumpableRng> makeArbitraryJumpsSpliterator(long index, long fence, double distance) {
- return new RandomArbitraryJumpsSpliterator(this, index, fence, distance);
+ Spliterator<ArbitrarilyJumpableRNG> makeArbitraryJumpsSpliterator(long index, long fence, double distance) {
+ return new RandomArbitraryJumpsSpliterator(this, index, fence, distance);
}
/* ---------------- public methods ---------------- */
@@ -126,79 +126,77 @@
*
* @return a new object that is a copy of this generator
*/
- public abstract AbstractArbitrarilyJumpableRng copy();
+ public abstract AbstractArbitrarilyJumpableRNG copy();
// Stream methods for jumping
+ private static <T> Stream<T> stream(Spliterator<T> srng) {
+ return StreamSupport.stream(srng, false);
+ }
+
/**
- * Returns an effectively unlimited stream of new pseudorandom
- * number generators, each of which implements the {@code Rng}
- * interface, produced by jumping copies of this generator
- * by different integer multiples of the default jump distance.
+ * Returns an effectively unlimited stream of new pseudorandom number generators, each of which
+ * implements the {@link RandomNumberGenerator} interface, produced by jumping copies of this
+ * generator by different integer multiples of the default jump distance.
*
- * @implNote This method is implemented to be equivalent to
- * {@code jumps(Long.MAX_VALUE)}.
+ * @return a stream of objects that implement the {@link RandomNumberGenerator} interface
*
- * @return a stream of objects that implement the {@code Rng} interface
+ * @implNote This method is implemented to be equivalent to {@code
+ * jumps(Long.MAX_VALUE)}.
*/
- public Stream<Rng> jumps() {
- return StreamSupport.stream
- (makeJumpsSpliterator(0L, Long.MAX_VALUE, defaultJumpDistance()),
- false);
+ public Stream<RandomNumberGenerator> jumps() {
+ return stream(makeJumpsSpliterator(0L, Long.MAX_VALUE, defaultJumpDistance()));
}
/**
* Returns a stream producing the given {@code streamSize} number of
* new pseudorandom number generators, each of which implements the
- * {@code Rng} interface, produced by jumping copies of this generator
+ * {@link RandomNumberGenerator} interface, produced by jumping copies of this generator
* by different integer multiples of the default jump distance.
*
* @param streamSize the number of generators to generate
- * @return a stream of objects that implement the {@code Rng} interface
- * @throws IllegalArgumentException if {@code streamSize} is
- * less than zero
+ *
+ * @return a stream of objects that implement the {@link RandomNumberGenerator} interface
+ *
+ * @throws IllegalArgumentException if {@code streamSize} is less than zero
*/
- public Stream<Rng> jumps(long streamSize) {
- return StreamSupport.stream
- (makeJumpsSpliterator(0L, streamSize, defaultJumpDistance()),
- false);
+ public Stream<RandomNumberGenerator> jumps(long streamSize) {
+ RNGSupport.checkStreamSize(streamSize);
+ return stream(makeJumpsSpliterator(0L, streamSize, defaultJumpDistance()));
}
/**
- * Returns an effectively unlimited stream of new pseudorandom
- * number generators, each of which implements the {@code Rng}
- * 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)}.
+ * Returns an effectively unlimited stream of new pseudorandom number generators, each of which
+ * implements the {@link RandomNumberGenerator} interface, produced by jumping copies of this
+ * generator by different integer multiples of the specified jump distance.
*
* @param distance a distance to jump forward within the state cycle
- * @return a stream of objects that implement the {@code Rng} interface
+ *
+ * @return a stream of objects that implement the {@link RandomNumberGenerator} interface
+ *
+ * @implNote This method is implemented to be equivalent to {@code
+ * jumps(Long.MAX_VALUE)}.
*/
- public Stream<ArbitrarilyJumpableRng> jumps(double distance) {
- return StreamSupport.stream
- (makeArbitraryJumpsSpliterator(0L, Long.MAX_VALUE, distance),
- false);
+ public Stream<ArbitrarilyJumpableRNG> jumps(double distance) {
+ return stream(makeArbitraryJumpsSpliterator(0L, Long.MAX_VALUE, distance));
}
/**
- * Returns a stream producing the given {@code streamSize} number of
- * new pseudorandom number generators, each of which implements the
- * {@code Rng} interface, produced by jumping copies of this generator
- * by different integer multiples of the specified jump distance.
+ * Returns a stream producing the given {@code streamSize} number of new pseudorandom number
+ * generators, each of which implements the {@link RandomNumberGenerator} interface, produced by
+ * jumping copies of this generator by different integer multiples of the specified jump
+ * distance.
*
* @param streamSize the number of generators to generate
- * @param distance a distance to jump forward within the state cycle
- * @return a stream of objects that implement the {@code Rng} interface
- * @throws IllegalArgumentException if {@code streamSize} is
- * less than zero
+ * @param distance a distance to jump forward within the state cycle
+ *
+ * @return a stream of objects that implement the {@link RandomNumberGenerator} interface
+ *
+ * @throws IllegalArgumentException if {@code streamSize} is less than zero
*/
- public Stream<ArbitrarilyJumpableRng> jumps(long streamSize, double distance) {
- RngSupport.checkStreamSize(streamSize);
- return StreamSupport.stream
- (makeArbitraryJumpsSpliterator(0L, streamSize, distance),
- false);
+ public Stream<ArbitrarilyJumpableRNG> jumps(long streamSize, double distance) {
+ RNGSupport.checkStreamSize(streamSize);
+ return stream(makeArbitraryJumpsSpliterator(0L, streamSize, distance));
}
/**
@@ -207,81 +205,75 @@
* or more) within its state cycle. The distance used is that
* returned by method {@code defaultLeapDistance()}.
*/
- public void leap() { jump(defaultLeapDistance()); }
+ public void leap() {
+ jump(defaultLeapDistance());
+ }
// Stream methods for leaping
/**
- * Returns an effectively unlimited stream of new pseudorandom
- * number generators, each of which implements the {@code Rng}
- * interface, produced by jumping copies of this generator
- * by different integer multiples of the default leap distance.
+ * Returns an effectively unlimited stream of new pseudorandom number generators, each of which
+ * implements the {@link RandomNumberGenerator} interface, produced by jumping copies of this
+ * generator by different integer multiples of the default leap distance.
*
- * @implNote This method is implemented to be equivalent to
- * {@code leaps(Long.MAX_VALUE)}.
+ * @implNote This method is implemented to be equivalent to {@code leaps(Long.MAX_VALUE)}.
*
- * @return a stream of objects that implement the {@code Rng} interface
+ * @return a stream of objects that implement the {@link RandomNumberGenerator} interface
*/
- public Stream<JumpableRng> leaps() {
- return StreamSupport.stream
- (makeLeapsSpliterator(0L, Long.MAX_VALUE, defaultLeapDistance()),
- false);
+ public Stream<JumpableRNG> leaps() {
+ return stream(makeLeapsSpliterator(0L, Long.MAX_VALUE, defaultLeapDistance()));
}
/**
- * Returns a stream producing the given {@code streamSize} number of
- * new pseudorandom number generators, each of which implements the
- * {@code Rng} interface, produced by jumping copies of this generator
- * by different integer multiples of the default leap distance.
+ * Returns a stream producing the given {@code streamSize} number of new pseudorandom number
+ * generators, each of which implements the {@link RandomNumberGenerator} interface, produced by
+ * jumping copies of this generator by different integer multiples of the default leap
+ * distance.
*
* @param streamSize the number of generators to generate
- * @return a stream of objects that implement the {@code Rng} interface
- * @throws IllegalArgumentException if {@code streamSize} is
- * less than zero
+ *
+ * @return a stream of objects that implement the {@link RandomNumberGenerator} interface
+ *
+ * @throws IllegalArgumentException if {@code streamSize} is less than zero
*/
- public Stream<JumpableRng> leaps(long streamSize) {
- return StreamSupport.stream
- (makeLeapsSpliterator(0L, streamSize, defaultLeapDistance()),
- false);
+ public Stream<JumpableRNG> leaps(long streamSize) {
+ return stream(makeLeapsSpliterator(0L, streamSize, defaultLeapDistance()));
}
-
+
/**
- * 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, we choose to override the method
- * {@code trySplit()} to try to optimize execution speed: instead of
- * dividing a range in half, it breaks off the largest possible chunk
- * whose size is a power of two such that the remaining chunk is not
- * empty. In this way, the necessary jump distances will tend to be
- * powers of two. The long and double versions of this class are
- * identical except for types.
+ * 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
+ * {@code Long.MAX_VALUE}. For splits, we choose to override the method {@code trySplit()} to
+ * try to optimize execution speed: instead of dividing a range in half, it breaks off the
+ * largest possible chunk whose size is a power of two such that the remaining chunk is not
+ * empty. In this way, the necessary jump distances will tend to be powers of two. The long
+ * and double versions of this class are identical except for types.
*/
- static class RandomIntsSpliterator extends RngSupport.RandomSpliterator implements Spliterator.OfInt {
- final ArbitrarilyJumpableRng generatingRng;
+ static class RandomIntsSpliterator extends RNGSupport.RandomSpliterator implements Spliterator.OfInt {
+ final ArbitrarilyJumpableRNG generatingRNG;
final int origin;
final int bound;
- RandomIntsSpliterator(ArbitrarilyJumpableRng generatingRng, long index, long fence, int origin, int bound) {
- super(index, fence);
- this.origin = origin; this.bound = bound;
- this.generatingRng = generatingRng;
+ RandomIntsSpliterator(ArbitrarilyJumpableRNG generatingRNG, long index, long fence, int origin, int bound) {
+ super(index, fence);
+ this.origin = origin; this.bound = bound;
+ this.generatingRNG = generatingRNG;
}
-
+
public Spliterator.OfInt trySplit() {
long i = index, delta = Long.highestOneBit((fence - i) - 1), m = i + delta;
- if (m <= i) return null;
- index = m;
- ArbitrarilyJumpableRng r = generatingRng;
- return new RandomIntsSpliterator(r.copyAndJump((double)delta), i, m, origin, bound);
+ if (m <= i) return null;
+ index = m;
+ ArbitrarilyJumpableRNG r = generatingRNG;
+ return new RandomIntsSpliterator(r.copyAndJump((double)delta), i, m, origin, bound);
}
-
+
public boolean tryAdvance(IntConsumer consumer) {
if (consumer == null) throw new NullPointerException();
long i = index, f = fence;
if (i < f) {
- consumer.accept(RngSupport.boundedNextInt(generatingRng, origin, bound));
+ consumer.accept(RNGSupport.boundedNextInt(generatingRNG, origin, bound));
index = i + 1;
return true;
}
@@ -293,42 +285,42 @@
long i = index, f = fence;
if (i < f) {
index = f;
- ArbitrarilyJumpableRng r = generatingRng;
+ ArbitrarilyJumpableRNG r = generatingRNG;
int o = origin, b = bound;
do {
- consumer.accept(RngSupport.boundedNextInt(r, o, b));
+ consumer.accept(RNGSupport.boundedNextInt(r, o, b));
} while (++i < f);
}
}
}
/**
- * Spliterator for long streams.
+ * Spliterator for long streams.
*/
- static class RandomLongsSpliterator extends RngSupport.RandomSpliterator implements Spliterator.OfLong {
- final ArbitrarilyJumpableRng generatingRng;
+ static class RandomLongsSpliterator extends RNGSupport.RandomSpliterator implements Spliterator.OfLong {
+ final ArbitrarilyJumpableRNG generatingRNG;
final long origin;
final long bound;
- RandomLongsSpliterator(ArbitrarilyJumpableRng generatingRng, long index, long fence, long origin, long bound) {
- super(index, fence);
- this.generatingRng = generatingRng;
- this.origin = origin; this.bound = bound;
+ RandomLongsSpliterator(ArbitrarilyJumpableRNG generatingRNG, long index, long fence, long origin, long bound) {
+ super(index, fence);
+ this.generatingRNG = generatingRNG;
+ this.origin = origin; this.bound = bound;
}
-
+
public Spliterator.OfLong trySplit() {
long i = index, delta = Long.highestOneBit((fence - i) - 1), m = i + delta;
- if (m <= i) return null;
- index = m;
- ArbitrarilyJumpableRng r = generatingRng;
- return new RandomLongsSpliterator(r.copyAndJump((double)delta), i, m, origin, bound);
+ if (m <= i) return null;
+ index = m;
+ ArbitrarilyJumpableRNG r = generatingRNG;
+ return new RandomLongsSpliterator(r.copyAndJump((double)delta), i, m, origin, bound);
}
-
+
public boolean tryAdvance(LongConsumer consumer) {
if (consumer == null) throw new NullPointerException();
long i = index, f = fence;
if (i < f) {
- consumer.accept(RngSupport.boundedNextLong(generatingRng, origin, bound));
+ consumer.accept(RNGSupport.boundedNextLong(generatingRNG, origin, bound));
index = i + 1;
return true;
}
@@ -340,43 +332,43 @@
long i = index, f = fence;
if (i < f) {
index = f;
- ArbitrarilyJumpableRng r = generatingRng;
+ ArbitrarilyJumpableRNG r = generatingRNG;
long o = origin, b = bound;
do {
- consumer.accept(RngSupport.boundedNextLong(r, o, b));
+ consumer.accept(RNGSupport.boundedNextLong(r, o, b));
} while (++i < f);
}
}
}
/**
- * Spliterator for double streams.
+ * Spliterator for double streams.
*/
- static class RandomDoublesSpliterator extends RngSupport.RandomSpliterator implements Spliterator.OfDouble {
- final ArbitrarilyJumpableRng generatingRng;
+ static class RandomDoublesSpliterator extends RNGSupport.RandomSpliterator implements Spliterator.OfDouble {
+ final ArbitrarilyJumpableRNG generatingRNG;
final double origin;
final double bound;
- RandomDoublesSpliterator(ArbitrarilyJumpableRng generatingRng, long index, long fence, double origin, double bound) {
- super(index, fence);
- this.generatingRng = generatingRng;
- this.origin = origin; this.bound = bound;
+ RandomDoublesSpliterator(ArbitrarilyJumpableRNG generatingRNG, long index, long fence, double origin, double bound) {
+ super(index, fence);
+ this.generatingRNG = generatingRNG;
+ this.origin = origin; this.bound = bound;
}
-
+
public Spliterator.OfDouble trySplit() {
long i = index, delta = Long.highestOneBit((fence - i) - 1), m = i + delta;
- if (m <= i) return null;
- index = m;
- ArbitrarilyJumpableRng r = generatingRng;
- return new RandomDoublesSpliterator(r.copyAndJump((double)delta), i, m, origin, bound);
+ if (m <= i) return null;
+ index = m;
+ ArbitrarilyJumpableRNG r = generatingRNG;
+ return new RandomDoublesSpliterator(r.copyAndJump((double)delta), i, m, origin, bound);
}
-
+
public boolean tryAdvance(DoubleConsumer consumer) {
if (consumer == null) throw new NullPointerException();
long i = index, f = fence;
if (i < f) {
- consumer.accept(RngSupport.boundedNextDouble(generatingRng, origin, bound));
+ consumer.accept(RNGSupport.boundedNextDouble(generatingRNG, origin, bound));
index = i + 1;
return true;
}
@@ -388,15 +380,15 @@
long i = index, f = fence;
if (i < f) {
index = f;
- ArbitrarilyJumpableRng r = generatingRng;
+ ArbitrarilyJumpableRNG r = generatingRNG;
double o = origin, b = bound;
do {
- consumer.accept(RngSupport.boundedNextDouble(r, o, b));
+ consumer.accept(RNGSupport.boundedNextDouble(r, o, b));
} while (++i < f);
}
}
}
-
+
// Spliterators for producing new generators by jumping or leaping. The
// complete implementation of each of these spliterators is right here.
// In the same manner as for the preceding spliterators, the method trySplit() is
@@ -407,87 +399,43 @@
// powers of two.
/**
- * Spliterator for stream of generators of type Rng produced by jumps.
+ * Spliterator for stream of generators of type RandomNumberGenerator produced by jumps.
*/
- static class RandomJumpsSpliterator extends RngSupport.RandomSpliterator implements Spliterator<Rng> {
- ArbitrarilyJumpableRng generatingRng;
- final double distance;
+ static class RandomJumpsSpliterator extends RNGSupport.RandomSpliterator implements Spliterator<RandomNumberGenerator> {
+ ArbitrarilyJumpableRNG generatingRNG;
+ final double distance;
- RandomJumpsSpliterator(ArbitrarilyJumpableRng generatingRng, long index, long fence, double distance) {
+ RandomJumpsSpliterator(ArbitrarilyJumpableRNG generatingRNG, long index, long fence, double distance) {
super(index, fence);
- this.generatingRng = generatingRng; this.distance = distance;
+ this.generatingRNG = generatingRNG; this.distance = distance;
}
- public Spliterator<Rng> trySplit() {
- long i = index, delta = Long.highestOneBit((fence - i) - 1), m = i + delta;
- if (m <= i) return null;
- index = m;
- ArbitrarilyJumpableRng r = generatingRng;
- // Because delta is a power of two, (distance * (double)delta) can always be computed exactly.
- return new RandomJumpsSpliterator(r.copyAndJump(distance * (double)delta), i, m, distance);
+ public Spliterator<RandomNumberGenerator> trySplit() {
+ long i = index, delta = Long.highestOneBit((fence - i) - 1), m = i + delta;
+ if (m <= i) return null;
+ index = m;
+ ArbitrarilyJumpableRNG r = generatingRNG;
+ // Because delta is a power of two, (distance * (double)delta) can always be computed exactly.
+ return new RandomJumpsSpliterator(r.copyAndJump(distance * (double)delta), i, m, distance);
}
- public boolean tryAdvance(Consumer<? super Rng> consumer) {
+ public boolean tryAdvance(Consumer<? super RandomNumberGenerator> consumer) {
if (consumer == null) throw new NullPointerException();
long i = index, f = fence;
if (i < f) {
- consumer.accept(generatingRng.copyAndJump(distance));
+ consumer.accept(generatingRNG.copyAndJump(distance));
index = i + 1;
return true;
}
return false;
}
- public void forEachRemaining(Consumer<? super Rng> consumer) {
+ public void forEachRemaining(Consumer<? super RandomNumberGenerator> consumer) {
if (consumer == null) throw new NullPointerException();
long i = index, f = fence;
if (i < f) {
index = f;
- ArbitrarilyJumpableRng r = generatingRng;
- do {
- consumer.accept(r.copyAndJump(distance));
- } while (++i < f);
- }
- }
- }
-
- /**
- * Spliterator for stream of generators of type Rng produced by leaps.
- */
- static class RandomLeapsSpliterator extends RngSupport.RandomSpliterator implements Spliterator<JumpableRng> {
- ArbitrarilyJumpableRng generatingRng;
- final double distance;
-
- RandomLeapsSpliterator(ArbitrarilyJumpableRng generatingRng, long index, long fence, double distance) {
- super(index, fence);
- this.generatingRng = generatingRng; this.distance = distance;
- }
-
- public Spliterator<JumpableRng> trySplit() {
- long i = index, delta = Long.highestOneBit((fence - i) - 1), m = i + delta;
- if (m <= i) return null;
- index = m;
- // Because delta is a power of two, (distance * (double)delta) can always be computed exactly.
- return new RandomLeapsSpliterator(generatingRng.copyAndJump(distance * (double)delta), i, m, distance);
- }
-
- public boolean tryAdvance(Consumer<? super JumpableRng> consumer) {
- if (consumer == null) throw new NullPointerException();
- long i = index, f = fence;
- if (i < f) {
- consumer.accept(generatingRng.copyAndJump(distance));
- index = i + 1;
- return true;
- }
- return false;
- }
-
- public void forEachRemaining(Consumer<? super JumpableRng> consumer) {
- if (consumer == null) throw new NullPointerException();
- long i = index, f = fence;
- if (i < f) {
- index = f;
- ArbitrarilyJumpableRng r = generatingRng;
+ ArbitrarilyJumpableRNG r = generatingRNG;
do {
consumer.accept(r.copyAndJump(distance));
} while (++i < f);
@@ -496,42 +444,86 @@
}
/**
- * Spliterator for stream of generators of type Rng produced by arbitrary jumps.
+ * Spliterator for stream of generators of type RandomNumberGenerator produced by leaps.
*/
- static class RandomArbitraryJumpsSpliterator extends RngSupport.RandomSpliterator implements Spliterator<ArbitrarilyJumpableRng> {
- ArbitrarilyJumpableRng generatingRng;
- final double distance;
+ static class RandomLeapsSpliterator extends RNGSupport.RandomSpliterator implements Spliterator<JumpableRNG> {
+ ArbitrarilyJumpableRNG generatingRNG;
+ final double distance;
- RandomArbitraryJumpsSpliterator(ArbitrarilyJumpableRng generatingRng, long index, long fence, double distance) {
+ RandomLeapsSpliterator(ArbitrarilyJumpableRNG generatingRNG, long index, long fence, double distance) {
super(index, fence);
- this.generatingRng = generatingRng; this.distance = distance;
+ this.generatingRNG = generatingRNG; this.distance = distance;
}
- public Spliterator<ArbitrarilyJumpableRng> trySplit() {
- long i = index, delta = Long.highestOneBit((fence - i) - 1), m = i + delta;
- if (m <= i) return null;
- index = m;
- // Because delta is a power of two, (distance * (double)delta) can always be computed exactly.
- return new RandomArbitraryJumpsSpliterator(generatingRng.copyAndJump(distance * (double)delta), i, m, distance);
+ public Spliterator<JumpableRNG> trySplit() {
+ long i = index, delta = Long.highestOneBit((fence - i) - 1), m = i + delta;
+ if (m <= i) return null;
+ index = m;
+ // Because delta is a power of two, (distance * (double)delta) can always be computed exactly.
+ return new RandomLeapsSpliterator(generatingRNG.copyAndJump(distance * (double)delta), i, m, distance);
}
- public boolean tryAdvance(Consumer<? super ArbitrarilyJumpableRng> consumer) {
+ public boolean tryAdvance(Consumer<? super JumpableRNG> consumer) {
if (consumer == null) throw new NullPointerException();
long i = index, f = fence;
if (i < f) {
- consumer.accept(generatingRng.copyAndJump(distance));
+ consumer.accept(generatingRNG.copyAndJump(distance));
index = i + 1;
return true;
}
return false;
}
- public void forEachRemaining(Consumer<? super ArbitrarilyJumpableRng> consumer) {
+ public void forEachRemaining(Consumer<? super JumpableRNG> consumer) {
if (consumer == null) throw new NullPointerException();
long i = index, f = fence;
if (i < f) {
index = f;
- ArbitrarilyJumpableRng r = generatingRng;
+ ArbitrarilyJumpableRNG r = generatingRNG;
+ do {
+ consumer.accept(r.copyAndJump(distance));
+ } while (++i < f);
+ }
+ }
+ }
+
+ /**
+ * Spliterator for stream of generators of type RandomNumberGenerator produced by arbitrary jumps.
+ */
+ static class RandomArbitraryJumpsSpliterator extends RNGSupport.RandomSpliterator implements Spliterator<ArbitrarilyJumpableRNG> {
+ ArbitrarilyJumpableRNG generatingRNG;
+ final double distance;
+
+ RandomArbitraryJumpsSpliterator(ArbitrarilyJumpableRNG generatingRNG, long index, long fence, double distance) {
+ super(index, fence);
+ this.generatingRNG = generatingRNG; this.distance = distance;
+ }
+
+ public Spliterator<ArbitrarilyJumpableRNG> trySplit() {
+ long i = index, delta = Long.highestOneBit((fence - i) - 1), m = i + delta;
+ if (m <= i) return null;
+ index = m;
+ // Because delta is a power of two, (distance * (double)delta) can always be computed exactly.
+ return new RandomArbitraryJumpsSpliterator(generatingRNG.copyAndJump(distance * (double)delta), i, m, distance);
+ }
+
+ public boolean tryAdvance(Consumer<? super ArbitrarilyJumpableRNG> consumer) {
+ if (consumer == null) throw new NullPointerException();
+ long i = index, f = fence;
+ if (i < f) {
+ consumer.accept(generatingRNG.copyAndJump(distance));
+ index = i + 1;
+ return true;
+ }
+ return false;
+ }
+
+ public void forEachRemaining(Consumer<? super ArbitrarilyJumpableRNG> consumer) {
+ if (consumer == null) throw new NullPointerException();
+ long i = index, f = fence;
+ if (i < f) {
+ index = f;
+ ArbitrarilyJumpableRNG r = generatingRNG;
do {
consumer.accept(r.copyAndJump(distance));
} while (++i < f);
--- a/src/java.base/share/classes/java/util/random/AbstractSharedRNG.java Thu Jun 27 18:02:51 2019 -0300
+++ b/src/java.base/share/classes/java/util/random/AbstractSharedRNG.java Thu Jun 27 18:30:27 2019 -0300
@@ -22,18 +22,16 @@
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
-package java.util;
+
+package java.util.random;
import java.util.Spliterator;
-import java.util.function.Consumer;
+import java.util.function.DoubleConsumer;
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 Rng}
+ * This class provides much of the implementation of the {@link RandomNumberGenerator}
* interface, to minimize the effort required to implement that interface.
*
* To implement a pseudorandom number generator, the programmer needs
@@ -42,16 +40,14 @@
* the implementations of other methods in this class to operate
* correctly, it must be safe for multiple threads to call these
* methods on that same object. The principal purpose of this class
- * is to support the implementations of {@code java.util.Random}
+ * is to support the implementations of {@link java.util.Random}
* and {@code java.util.concurrent.ThreadLocalRandom}, but it could
* in principle be used to implement others as well.
*
* (If the pseudorandom number generator has the ability to split or
* jump, then the programmer may wish to consider instead extending
- * another abstract class, such as {@code AbstractSplittableRng},
- * {@code AbstractJumpableRng}, {@code AbstractArbitrarilyJumpableRng},
- * {@code AbstractSplittableJumpableRng}, or
- * {@code AbstractSplittableArbitrarilyJumpableRng}.)
+ * another abstract class, such as {@link AbstractSplittableRNG},
+ * {@link ArbitrarilyJumpableRNG}, or {@link AbstractArbitrarilyJumpableRNG}.)
*
* The programmer should generally provide at least three constructors:
* one that takes no arguments, one that accepts a {@code long}
@@ -61,7 +57,7 @@
* 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
+ * this class provides {@link Spliterator}-based implementations that
* allow parallel execution when appropriate.
*
* The documentation for each non-abstract method in this class
@@ -69,64 +65,62 @@
* be overridden if the pseudorandom number generator being
* implemented admits a more efficient implementation.
*
- * @author Guy Steele
- * @author Doug Lea
- * @since 1.9
+ * @since 14
*/
-public abstract class AbstractSharedRng extends AbstractSpliteratorRng {
-
+public abstract class AbstractSharedRNG extends AbstractSpliteratorRNG {
/*
* Implementation Overview.
*
* This class provides most of the "user API" methods needed to
- * satisfy the interface java.util.Rng. Most of these methods
- * are in turn inherited from AbstractRng and the non-public class
- * AbstractSpliteratorRng; this file implements methods and spliterators
+ * satisfy the interface RandomNumberGenerator. Most of these methods
+ * are in turn inherited from AbstractRNG and the non-public class
+ * AbstractSpliteratorRNG; this file implements methods and spliterators
* necessary to support the latter.
*
* File organization: First some non-public methods, followed by
* some custom spliterator classes needed for stream methods.
*/
- // Methods required by class AbstractSpliteratorRng
+ // Methods required by class AbstractSpliteratorRNG
Spliterator.OfInt makeIntsSpliterator(long index, long fence, int origin, int bound) {
- return new RandomIntsSpliterator(this, index, fence, origin, 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);
+ 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);
+ return new RandomDoublesSpliterator(this, index, fence, origin, bound);
}
- // Spliterators for producing streams. These are based on abstract
- // spliterator classes provided by class AbstractSpliteratorRng.
- // Each one needs to define only a constructor and two methods.
-
- static class RandomIntsSpliterator extends RngSupport.RandomSpliterator implements Spliterator.OfInt {
- final AbstractSharedRng generatingRng;
+ /**
+ * Spliterators for producing streams. These are based on abstract spliterator classes provided
+ * by class AbstractSpliteratorRNG. Each one needs to define only a constructor and two
+ * methods.
+ */
+ static class RandomIntsSpliterator extends RNGSupport.RandomSpliterator implements Spliterator.OfInt {
+ final AbstractSharedRNG generatingRNG;
final int origin;
final int bound;
- RandomIntsSpliterator(AbstractSharedRng generatingRng, long index, long fence, int origin, int bound) {
- super(index, fence);
- this.generatingRng = generatingRng;
+ RandomIntsSpliterator(AbstractSharedRNG generatingRNG, long index, long fence, int origin, int bound) {
+ super(index, fence);
+ this.generatingRNG = generatingRNG;
this.origin = origin; this.bound = bound;
}
-
+
public Spliterator.OfInt trySplit() {
long i = index, m = (i + fence) >>> 1;
- if (m <= i) return null;
- index = m;
- // The same generatingRng is used, with no splitting or copying.
- return new RandomIntsSpliterator(generatingRng, i, m, origin, bound);
+ if (m <= i) return null;
+ index = m;
+ // The same generatingRNG is used, with no splitting or copying.
+ return new RandomIntsSpliterator(generatingRNG, i, m, origin, bound);
}
public boolean tryAdvance(IntConsumer consumer) {
if (consumer == null) throw new NullPointerException();
long i = index, f = fence;
if (i < f) {
- consumer.accept(RngSupport.boundedNextInt(generatingRng, origin, bound));
+ consumer.accept(RNGSupport.boundedNextInt(generatingRNG, origin, bound));
index = i + 1;
return true;
}
@@ -138,10 +132,10 @@
long i = index, f = fence;
if (i < f) {
index = f;
- Rng r = generatingRng;
+ RandomNumberGenerator r = generatingRNG;
int o = origin, b = bound;
do {
- consumer.accept(RngSupport.boundedNextInt(r, o, b));
+ consumer.accept(RNGSupport.boundedNextInt(r, o, b));
} while (++i < f);
}
}
@@ -150,30 +144,30 @@
/**
* Spliterator for long streams.
*/
- static class RandomLongsSpliterator extends RngSupport.RandomSpliterator implements Spliterator.OfLong {
- final AbstractSharedRng generatingRng;
+ static class RandomLongsSpliterator extends RNGSupport.RandomSpliterator implements Spliterator.OfLong {
+ final AbstractSharedRNG generatingRNG;
final long origin;
final long bound;
- RandomLongsSpliterator(AbstractSharedRng generatingRng, long index, long fence, long origin, long bound) {
- super(index, fence);
- this.generatingRng = generatingRng;
+ RandomLongsSpliterator(AbstractSharedRNG generatingRNG, long index, long fence, long origin, long bound) {
+ super(index, fence);
+ this.generatingRNG = generatingRNG;
this.origin = origin; this.bound = bound;
}
-
+
public Spliterator.OfLong trySplit() {
long i = index, m = (i + fence) >>> 1;
- if (m <= i) return null;
- index = m;
- // The same generatingRng is used, with no splitting or copying.
- return new RandomLongsSpliterator(generatingRng, i, m, origin, bound);
+ if (m <= i) return null;
+ index = m;
+ // The same generatingRNG is used, with no splitting or copying.
+ return new RandomLongsSpliterator(generatingRNG, i, m, origin, bound);
}
public boolean tryAdvance(LongConsumer consumer) {
if (consumer == null) throw new NullPointerException();
long i = index, f = fence;
if (i < f) {
- consumer.accept(RngSupport.boundedNextLong(generatingRng, origin, bound));
+ consumer.accept(RNGSupport.boundedNextLong(generatingRNG, origin, bound));
index = i + 1;
return true;
}
@@ -185,10 +179,10 @@
long i = index, f = fence;
if (i < f) {
index = f;
- Rng r = generatingRng;
+ RandomNumberGenerator r = generatingRNG;
long o = origin, b = bound;
do {
- consumer.accept(RngSupport.boundedNextLong(r, o, b));
+ consumer.accept(RNGSupport.boundedNextLong(r, o, b));
} while (++i < f);
}
}
@@ -197,30 +191,30 @@
/**
* Spliterator for double streams.
*/
- static class RandomDoublesSpliterator extends RngSupport.RandomSpliterator implements Spliterator.OfDouble {
- final AbstractSharedRng generatingRng;
+ static class RandomDoublesSpliterator extends RNGSupport.RandomSpliterator implements Spliterator.OfDouble {
+ final AbstractSharedRNG generatingRNG;
final double origin;
final double bound;
- RandomDoublesSpliterator(AbstractSharedRng generatingRng, long index, long fence, double origin, double bound) {
- super(index, fence);
- this.generatingRng = generatingRng;
+ RandomDoublesSpliterator(AbstractSharedRNG generatingRNG, long index, long fence, double origin, double bound) {
+ super(index, fence);
+ this.generatingRNG = generatingRNG;
this.origin = origin; this.bound = bound;
}
-
+
public Spliterator.OfDouble trySplit() {
long i = index, m = (i + fence) >>> 1;
- if (m <= i) return null;
- index = m;
- // The same generatingRng is used, with no splitting or copying.
- return new RandomDoublesSpliterator(generatingRng, i, m, origin, bound);
+ if (m <= i) return null;
+ index = m;
+ // The same generatingRNG is used, with no splitting or copying.
+ return new RandomDoublesSpliterator(generatingRNG, i, m, origin, bound);
}
public boolean tryAdvance(DoubleConsumer consumer) {
if (consumer == null) throw new NullPointerException();
long i = index, f = fence;
if (i < f) {
- consumer.accept(RngSupport.boundedNextDouble(generatingRng, origin, bound));
+ consumer.accept(RNGSupport.boundedNextDouble(generatingRNG, origin, bound));
index = i + 1;
return true;
}
@@ -232,10 +226,10 @@
long i = index, f = fence;
if (i < f) {
index = f;
- Rng r = generatingRng;
+ RandomNumberGenerator r = generatingRNG;
double o = origin, b = bound;
do {
- consumer.accept(RngSupport.boundedNextDouble(r, o, b));
+ consumer.accept(RNGSupport.boundedNextDouble(r, o, b));
} while (++i < f);
}
}
--- a/src/java.base/share/classes/java/util/random/AbstractSpliteratorRNG.java Thu Jun 27 18:02:51 2019 -0300
+++ b/src/java.base/share/classes/java/util/random/AbstractSpliteratorRNG.java Thu Jun 27 18:30:27 2019 -0300
@@ -22,21 +22,19 @@
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
-package java.util;
+
+package java.util.random;
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;
+import java.util.stream.DoubleStream;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
-import java.util.stream.DoubleStream;
+import java.util.stream.StreamSupport;
/**
* This class overrides the stream-producing methods (such as {@code ints()})
- * in class {@code AbstractRng} to provide {@code Spliterator}-based
+ * in class {@link AbstractRNG} to provide {@link Spliterator}-based
* implmentations that support potentially parallel execution.
*
* To implement a pseudorandom number generator, the programmer needs
@@ -45,20 +43,18 @@
* {@code makeLongsSpliterator}, and {@code makeDoublesSpliterator}.
*
* This class is not public; it provides shared code to the public
- * classes {@code AbstractSplittableRng}, {@code AbstractSharedRng},
- * and {@code AbstractArbitrarilyJumpableRng}.
+ * classes {@link AbstractSplittableRNG}, {@link AbstractSharedRNG},
+ * and {@link AbstractArbitrarilyJumpableRNG}.
*
- * @author Guy Steele
- * @author Doug Lea
- * @since 1.9
+ * @since 14
*/
-abstract class AbstractSpliteratorRng implements Rng {
+abstract class AbstractSpliteratorRNG implements RandomNumberGenerator {
/*
* Implementation Overview.
*
* This class provides most of the "user API" methods needed to
- * satisfy the interface java.util.Rng. An implementation of this
+ * satisfy the interface RandomNumberGenerator. An implementation of this
* interface need only extend this class and provide implementations
* of six methods: nextInt, nextLong, and nextDouble (the versions
* that take no arguments) and makeIntsSpliterator,
@@ -71,27 +67,37 @@
abstract Spliterator.OfInt makeIntsSpliterator(long index, long fence, int origin, int bound);
abstract Spliterator.OfLong makeLongsSpliterator(long index, long fence, long origin, long bound);
abstract Spliterator.OfDouble makeDoublesSpliterator(long index, long fence, double origin, double bound);
-
+
/* ---------------- public methods ---------------- */
// stream methods, coded in a way intended to better isolate for
// maintenance purposes the small differences across forms.
+ private static IntStream intStream(Spliterator.OfInt srng) {
+ return StreamSupport.intStream(srng, false);
+ }
+
+ private static LongStream longStream(Spliterator.OfLong srng) {
+ return StreamSupport.longStream(srng, false);
+ }
+
+ private static DoubleStream doubleStream(Spliterator.OfDouble srng) {
+ return StreamSupport.doubleStream(srng, false);
+ }
+
/**
- * Returns a stream producing the given {@code streamSize} number
- * of pseudorandom {@code int} values from this generator and/or
- * one split from it.
+ * Returns a stream producing the given {@code streamSize} number of pseudorandom {@code int}
+ * values from this generator and/or one split from it.
*
* @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
+ *
+ * @throws IllegalArgumentException if {@code streamSize} is less than zero
*/
public IntStream ints(long streamSize) {
- RngSupport.checkStreamSize(streamSize);
- return StreamSupport.intStream
- (makeIntsSpliterator(0L, streamSize, Integer.MAX_VALUE, 0),
- false);
+ RNGSupport.checkStreamSize(streamSize);
+ return intStream(makeIntsSpliterator(0L, streamSize, Integer.MAX_VALUE, 0));
}
/**
@@ -103,215 +109,202 @@
*
* @return a stream of pseudorandomly chosen {@code int} values
*/
-
+
public IntStream ints() {
- return StreamSupport.intStream
- (makeIntsSpliterator(0L, Long.MAX_VALUE, Integer.MAX_VALUE, 0),
- false);
+ return intStream(makeIntsSpliterator(0L, Long.MAX_VALUE, Integer.MAX_VALUE, 0));
}
/**
- * Returns a stream producing the given {@code streamSize} number
- * of pseudorandom {@code int} values from this generator and/or one split
- * from it; each value conforms to the given origin (inclusive) and bound
- * (exclusive).
+ * Returns a stream producing the given {@code streamSize} number of pseudorandom {@code int}
+ * values from this generator and/or one split from it; each value conforms to the given origin
+ * (inclusive) and bound (exclusive).
*
- * @param streamSize the number of values to generate
+ * @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}
+ * @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}
*/
- public IntStream ints(long streamSize, int randomNumberOrigin,
- int randomNumberBound) {
- RngSupport.checkStreamSize(streamSize);
- RngSupport.checkRange(randomNumberOrigin, randomNumberBound);
- return StreamSupport.intStream
- (makeIntsSpliterator(0L, streamSize, randomNumberOrigin, randomNumberBound),
- false);
+ public IntStream ints(long streamSize, int randomNumberOrigin, int randomNumberBound) {
+ RNGSupport.checkStreamSize(streamSize);
+ RNGSupport.checkRange(randomNumberOrigin, randomNumberBound);
+ return intStream(makeIntsSpliterator(0L, streamSize, randomNumberOrigin, randomNumberBound));
}
/**
- * Returns an effectively unlimited stream of pseudorandom {@code
- * int} values from this generator and/or one split from it; each value
- * conforms to the given origin (inclusive) and bound (exclusive).
- *
- * @implNote This method is implemented to be equivalent to {@code
- * ints(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
+ * Returns an effectively unlimited stream of pseudorandom {@code int} values from this
+ * generator and/or one split from it; each value conforms to the given origin (inclusive) and
+ * bound (exclusive).
*
* @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}
+ * @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}
+ *
+ * @implNote This method is implemented to be equivalent to {@code ints(Long.MAX_VALUE,
+ * randomNumberOrigin, randomNumberBound)}.
*/
public IntStream ints(int randomNumberOrigin, int randomNumberBound) {
- RngSupport.checkRange(randomNumberOrigin, randomNumberBound);
- return StreamSupport.intStream
- (makeIntsSpliterator(0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
- false);
+ RNGSupport.checkRange(randomNumberOrigin, randomNumberBound);
+ return intStream(makeIntsSpliterator(0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound));
}
/**
- * Returns a stream producing the given {@code streamSize} number
- * of pseudorandom {@code long} values from this generator and/or
- * one split from it.
+ * Returns a stream producing the given {@code streamSize} number of pseudorandom {@code long}
+ * values from this generator and/or one split from it.
*
* @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
+ *
+ * @throws IllegalArgumentException if {@code streamSize} is less than zero
*/
public LongStream longs(long streamSize) {
- RngSupport.checkStreamSize(streamSize);
- return StreamSupport.longStream
- (makeLongsSpliterator(0L, streamSize, Long.MAX_VALUE, 0L),
- false);
+ RNGSupport.checkStreamSize(streamSize);
+ return longStream(makeLongsSpliterator(0L, streamSize, Long.MAX_VALUE, 0L));
}
/**
- * Returns an effectively unlimited stream of pseudorandom {@code
- * long} values from this generator and/or one split from it.
+ * Returns an effectively unlimited stream of pseudorandom {@code long} values from this
+ * generator and/or one split from it.
+ *
+ * @return a 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
+ * longs(Long.MAX_VALUE)}.
*/
public LongStream longs() {
- return StreamSupport.longStream
- (makeLongsSpliterator(0L, Long.MAX_VALUE, Long.MAX_VALUE, 0L),
- false);
+ return longStream(makeLongsSpliterator(0L, Long.MAX_VALUE, Long.MAX_VALUE, 0L));
}
/**
- * Returns a stream producing the given {@code streamSize} number of
- * pseudorandom {@code long} values from this generator and/or one split
- * from it; each value conforms to the given origin (inclusive) and bound
- * (exclusive).
+ * Returns a stream producing the given {@code streamSize} number of pseudorandom {@code long}
+ * values from this generator and/or one split from it; each value conforms to the given origin
+ * (inclusive) and bound (exclusive).
*
- * @param streamSize the number of values to generate
+ * @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}
+ * @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}
*/
public LongStream longs(long streamSize, long randomNumberOrigin,
- long randomNumberBound) {
- RngSupport.checkStreamSize(streamSize);
- RngSupport.checkRange(randomNumberOrigin, randomNumberBound);
- return StreamSupport.longStream
- (makeLongsSpliterator(0L, streamSize, randomNumberOrigin, randomNumberBound),
- false);
+ long randomNumberBound) {
+ RNGSupport.checkStreamSize(streamSize);
+ RNGSupport.checkRange(randomNumberOrigin, randomNumberBound);
+ return longStream(makeLongsSpliterator(0L, streamSize, randomNumberOrigin, randomNumberBound));
}
/**
- * Returns an effectively unlimited stream of pseudorandom {@code
- * long} values from this generator and/or one split from it; each value
- * conforms to the given origin (inclusive) and bound (exclusive).
- *
- * @implNote This method is implemented to be equivalent to {@code
- * longs(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
+ * Returns an effectively unlimited stream of pseudorandom {@code long} values from this
+ * generator and/or one split from it; each value conforms to the given origin (inclusive) and
+ * bound (exclusive).
*
* @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}
+ * @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}
+ *
+ * @implNote This method is implemented to be equivalent to {@code longs(Long.MAX_VALUE,
+ * randomNumberOrigin, randomNumberBound)}.
*/
public LongStream longs(long randomNumberOrigin, long randomNumberBound) {
- RngSupport.checkRange(randomNumberOrigin, randomNumberBound);
+ RNGSupport.checkRange(randomNumberOrigin, randomNumberBound);
return StreamSupport.longStream
(makeLongsSpliterator(0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
false);
}
/**
- * Returns a stream producing the given {@code streamSize} number of
- * pseudorandom {@code double} values from this generator and/or one split
- * from it; each value is between zero (inclusive) and one (exclusive).
+ * Returns a stream producing the given {@code streamSize} number of pseudorandom {@code double}
+ * values from this generator and/or one split from it; each value is 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
+ *
+ * @throws IllegalArgumentException if {@code streamSize} is less than zero
*/
public DoubleStream doubles(long streamSize) {
- RngSupport.checkStreamSize(streamSize);
- return StreamSupport.doubleStream
- (makeDoublesSpliterator(0L, streamSize, Double.MAX_VALUE, 0.0),
- false);
+ RNGSupport.checkStreamSize(streamSize);
+ return doubleStream(makeDoublesSpliterator(0L, streamSize, Double.MAX_VALUE, 0.0));
}
/**
- * Returns an effectively unlimited stream of pseudorandom {@code
- * double} values from this generator and/or one split from it; each value
- * is between zero (inclusive) and one (exclusive).
+ * Returns an effectively unlimited stream of pseudorandom {@code double} values from this
+ * generator and/or one split from it; each value is between zero (inclusive) and one
+ * (exclusive).
+ *
+ * @return a stream of pseudorandom {@code double} values
*
* @implNote This method is implemented to be equivalent to {@code
- * doubles(Long.MAX_VALUE)}.
- *
- * @return a stream of pseudorandom {@code double} values
+ * doubles(Long.MAX_VALUE)}.
*/
public DoubleStream doubles() {
- return StreamSupport.doubleStream
- (makeDoublesSpliterator(0L, Long.MAX_VALUE, Double.MAX_VALUE, 0.0),
- false);
+ return doubleStream(makeDoublesSpliterator(0L, Long.MAX_VALUE, Double.MAX_VALUE, 0.0));
}
/**
- * Returns a stream producing the given {@code streamSize} number of
- * pseudorandom {@code double} values from this generator and/or one split
- * from it; each value conforms to the given origin (inclusive) and bound
- * (exclusive).
+ * Returns a stream producing the given {@code streamSize} number of pseudorandom {@code double}
+ * values from this generator and/or one split from it; each value conforms to the given origin
+ * (inclusive) and bound (exclusive).
*
- * @param streamSize the number of values to generate
+ * @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}
+ * @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}
*/
- public DoubleStream doubles(long streamSize, double randomNumberOrigin,
- double randomNumberBound) {
- RngSupport.checkStreamSize(streamSize);
- RngSupport.checkRange(randomNumberOrigin, randomNumberBound);
- return StreamSupport.doubleStream
- (makeDoublesSpliterator(0L, streamSize, randomNumberOrigin, randomNumberBound),
- false);
+ public DoubleStream doubles(long streamSize, double randomNumberOrigin, double randomNumberBound) {
+ RNGSupport.checkStreamSize(streamSize);
+ RNGSupport.checkRange(randomNumberOrigin, randomNumberBound);
+ return doubleStream(makeDoublesSpliterator(0L, streamSize, randomNumberOrigin, randomNumberBound));
}
/**
- * Returns an effectively unlimited stream of pseudorandom {@code
- * double} values from this generator and/or one split from it; each value
- * conforms to the given origin (inclusive) and bound (exclusive).
- *
- * @implNote This method is implemented to be equivalent to {@code
- * doubles(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
+ * Returns an effectively unlimited stream of pseudorandom {@code double} values from this
+ * generator and/or one split from it; each value conforms to the given origin (inclusive) and
+ * bound (exclusive).
*
* @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}
+ * @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}
+ *
+ * @implNote This method is implemented to be equivalent to {@code
+ * doubles(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
*/
public DoubleStream doubles(double randomNumberOrigin, double randomNumberBound) {
- RngSupport.checkRange(randomNumberOrigin, randomNumberBound);
- return StreamSupport.doubleStream
- (makeDoublesSpliterator(0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
- false);
+ RNGSupport.checkRange(randomNumberOrigin, randomNumberBound);
+ return doubleStream(makeDoublesSpliterator(0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound));
}
}
--- a/src/java.base/share/classes/java/util/random/AbstractSplittableRNG.java Thu Jun 27 18:02:51 2019 -0300
+++ b/src/java.base/share/classes/java/util/random/AbstractSplittableRNG.java Thu Jun 27 18:30:27 2019 -0300
@@ -22,87 +22,80 @@
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
-package java.util;
+
+package java.util.random;
+import java.util.Spliterator;
import java.util.function.Consumer;
+import java.util.function.DoubleConsumer;
import java.util.function.IntConsumer;
import java.util.function.LongConsumer;
-import java.util.function.DoubleConsumer;
-import java.util.Spliterator;
+import java.util.stream.Stream;
import java.util.stream.StreamSupport;
-import java.util.stream.Stream;
/**
- * This class provides much of the implementation of the {@code SplittableRng}
- * interface, to minimize the effort required to implement this 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 period()},
- * and {@code split(SplittableRng)}.
- *
- * (If the pseudorandom number generator also has the ability to jump,
- * then the programmer may wish to consider instead extending
- * the class {@code AbstractSplittableJumpableRng} or (if it can also leap)
- * {@code AbstractSplittableLeapableRng}. But if the pseudorandom number
- * generator furthermore has the ability to jump an arbitrary specified
- * distance, then the programmer may wish to consider instead extending
- * the class {@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.
- *
- * 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
+ * This class provides much of the implementation of the {@link SplittableRNG} interface, to
+ * minimize the effort required to implement this interface.
+ * <p>
+ * 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 period()},
+ * and {@code split(SplittableRNG)}.
+ * <p>
+ * (If the pseudorandom number generator also has the ability to jump, then the programmer may wish
+ * to consider instead extending the class {@link ArbitrarilyJumpableRNG}. But if the pseudorandom
+ * number generator furthermore has the ability to jump an arbitrary specified distance, then the
+ * programmer may wish to consider instead extending the class {@link
+ * AbstractArbitrarilyJumpableRNG}.)
+ * <p>
+ * 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.
+ * <p>
+ * For the stream methods (such as {@code ints()} and {@code splits()}), this class provides {@link
+ * Spliterator} based implementations that allow parallel execution when appropriate.
+ * <p>
+ * 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
- * @author Doug Lea
- * @since 1.9
+ * @since 14
*/
-public abstract class AbstractSplittableRng extends AbstractSpliteratorRng implements SplittableRng {
+public abstract class AbstractSplittableRNG extends AbstractSpliteratorRNG implements SplittableRNG {
/*
* Implementation Overview.
*
* This class provides most of the "user API" methods needed to
- * satisfy the interface java.util.JumpableRng. Most of these methods
- * are in turn inherited from AbstractRng and the non-public class
- * AbstractSpliteratorRng; this file implements two versions of the
+ * satisfy the interface JumpableRNG. Most of these methods
+ * are in turn inherited from AbstractRNG and the non-public class
+ * AbstractSpliteratorRNG; this file implements two versions of the
* splits method and defines the spliterators necessary to support
* them.
*
- * The abstract split() method from interface SplittableRng is redeclared
- * here so as to narrow the return type to AbstractSplittableRng.
+ * The abstract split() method from interface SplittableRNG is redeclared
+ * here so as to narrow the return type to AbstractSplittableRNG.
*
* File organization: First the non-public methods needed by the class
- * AbstractSpliteratorRng, then the main public methods, followed by some
+ * AbstractSpliteratorRNG, then the main public methods, followed by some
* custom spliterator classes.
*/
Spliterator.OfInt makeIntsSpliterator(long index, long fence, int origin, int bound) {
- return new RandomIntsSpliterator(this, index, fence, origin, 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);
+ return new RandomLongsSpliterator(this, index, fence, origin, bound);
}
- Spliterator<SplittableRng> makeSplitsSpliterator(long index, long fence, SplittableRng source) {
- return new RandomSplitsSpliterator(source, index, fence, this);
+ Spliterator.OfDouble makeDoublesSpliterator(long index, long fence, double origin, double bound) {
+ return new RandomDoublesSpliterator(this, index, fence, origin, bound);
+ }
+
+ Spliterator<SplittableRNG> makeSplitsSpliterator(long index, long fence, SplittableRNG source) {
+ return new RandomSplitsSpliterator(source, index, fence, this);
}
/* ---------------- public methods ---------------- */
@@ -110,112 +103,105 @@
/**
* Implements the @code{split()} method as {@code this.split(this) }.
*
- * @return the new {@code AbstractSplittableRng} instance
+ * @return the new {@link AbstractSplittableRNG} instance
*/
- public SplittableRng split() { return this.split(this); }
-
+ public SplittableRNG split() {
+ return this.split(this);
+ }
+
// Stream methods for splittings
/**
- * Returns an effectively unlimited stream of new pseudorandom
- * number generators, each of which implements the {@code SplittableRng}
- * interface.
- *
- * This pseudorandom number generator provides the
- * entropy used to seed the new ones.
+ * Returns an effectively unlimited stream of new pseudorandom number generators, each of which
+ * implements the {@link SplittableRNG} interface.
+ * <p>
+ * This pseudorandom number generator provides the entropy used to seed the new ones.
*
- * @implNote This method is implemented to be equivalent to
- * {@code splits(Long.MAX_VALUE)}.
+ * @return a stream of {@link SplittableRNG} objects
*
- * @return a stream of {@code SplittableRng} objects
+ * @implNote This method is implemented to be equivalent to {@code splits(Long.MAX_VALUE)}.
*/
- public Stream<SplittableRng> splits() {
+ public Stream<SplittableRNG> splits() {
return this.splits(Long.MAX_VALUE, this);
}
/**
- * Returns a stream producing the given {@code streamSize} number of
- * new pseudorandom number generators, each of which implements the
- * {@code SplittableRng} interface.
- *
- * This pseudorandom number generator provides the
- * entropy used to seed the new ones.
+ * Returns a stream producing the given {@code streamSize} number of new pseudorandom number
+ * generators, each of which implements the {@link SplittableRNG} interface.
+ * <p>
+ * This pseudorandom number generator provides the entropy used to seed the new ones.
*
* @param streamSize the number of values to generate
- * @return a stream of {@code SplittableRng} objects
- * @throws IllegalArgumentException if {@code streamSize} is
- * less than zero
+ *
+ * @return a stream of {@link SplittableRNG} objects
+ *
+ * @throws IllegalArgumentException if {@code streamSize} is less than zero
*/
- public Stream<SplittableRng> splits(long streamSize) {
- return this.splits(streamSize, this);
+ public Stream<SplittableRNG> splits(long streamSize) {
+ return this.splits(streamSize, this);
}
/**
- * Returns an effectively unlimited stream of new pseudorandom
- * number generators, each of which implements the {@code SplittableRng}
- * interface.
+ * Returns an effectively unlimited stream of new pseudorandom number generators, each of which
+ * implements the {@link SplittableRNG} interface.
*
- * @implNote This method is implemented to be equivalent to
- * {@code splits(Long.MAX_VALUE)}.
+ * @param source a {@link SplittableRNG} instance to be used instead of this one as a source of
+ * pseudorandom bits used to initialize the state of the new ones.
*
- * @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 stream of {@code SplittableRng} objects
+ * @return a stream of {@link SplittableRNG} objects
+ *
+ * @implNote This method is implemented to be equivalent to {@code splits(Long.MAX_VALUE)}.
*/
- public Stream<SplittableRng> splits(SplittableRng source) {
+ public Stream<SplittableRNG> splits(SplittableRNG source) {
return this.splits(Long.MAX_VALUE, source);
}
/**
- * Returns a stream producing the given {@code streamSize} number of
- * new pseudorandom number generators, each of which implements the
- * {@code SplittableRng} interface.
+ * Returns a stream producing the given {@code streamSize} number of new pseudorandom number
+ * generators, each of which implements the {@link SplittableRNG} interface.
*
* @param streamSize the number of values to generate
- * @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 stream of {@code SplittableRng} objects
- * @throws IllegalArgumentException if {@code streamSize} is
- * less than zero
+ * @param source a {@link 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 stream of {@link SplittableRNG} objects
+ *
+ * @throws IllegalArgumentException if {@code streamSize} is less than zero
*/
- public Stream<SplittableRng> splits(long streamSize, SplittableRng source) {
- RngSupport.checkStreamSize(streamSize);
+ public Stream<SplittableRNG> splits(long streamSize, SplittableRNG source) {
+ RNGSupport.checkStreamSize(streamSize);
return StreamSupport.stream(makeSplitsSpliterator(0L, streamSize, source), 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.
+ * 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
+ * {@code 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 class RandomIntsSpliterator extends RngSupport.RandomSpliterator implements Spliterator.OfInt {
- final SplittableRng generatingRng;
+ static class RandomIntsSpliterator extends RNGSupport.RandomSpliterator implements Spliterator.OfInt {
+ final SplittableRNG generatingRNG;
final int origin;
final int bound;
- RandomIntsSpliterator(SplittableRng generatingRng, long index, long fence, int origin, int bound) {
- super(index, fence);
- this.generatingRng = generatingRng;
+ RandomIntsSpliterator(SplittableRNG generatingRNG, long index, long fence, int origin, int bound) {
+ super(index, fence);
+ this.generatingRNG = generatingRNG;
this.origin = origin; this.bound = bound;
}
-
+
public Spliterator.OfInt trySplit() {
long i = index, m = (i + fence) >>> 1;
- if (m <= i) return null;
- index = m;
- return new RandomIntsSpliterator(generatingRng.split(), i, m, origin, bound);
+ if (m <= i) return null;
+ index = m;
+ return new RandomIntsSpliterator(generatingRNG.split(), i, m, origin, bound);
}
public boolean tryAdvance(IntConsumer consumer) {
if (consumer == null) throw new NullPointerException();
long i = index, f = fence;
if (i < f) {
- consumer.accept(RngSupport.boundedNextInt(generatingRng, origin, bound));
+ consumer.accept(RNGSupport.boundedNextInt(generatingRNG, origin, bound));
index = i + 1;
return true;
}
@@ -227,10 +213,10 @@
long i = index, f = fence;
if (i < f) {
index = f;
- Rng r = generatingRng;
+ RandomNumberGenerator r = generatingRNG;
int o = origin, b = bound;
do {
- consumer.accept(RngSupport.boundedNextInt(r, o, b));
+ consumer.accept(RNGSupport.boundedNextInt(r, o, b));
} while (++i < f);
}
}
@@ -239,29 +225,29 @@
/**
* Spliterator for long streams.
*/
- static class RandomLongsSpliterator extends RngSupport.RandomSpliterator implements Spliterator.OfLong {
- final SplittableRng generatingRng;
+ static class RandomLongsSpliterator extends RNGSupport.RandomSpliterator implements Spliterator.OfLong {
+ final SplittableRNG generatingRNG;
final long origin;
final long bound;
- RandomLongsSpliterator(SplittableRng generatingRng, long index, long fence, long origin, long bound) {
- super(index, fence);
- this.generatingRng = generatingRng;
+ RandomLongsSpliterator(SplittableRNG generatingRNG, long index, long fence, long origin, long bound) {
+ super(index, fence);
+ this.generatingRNG = generatingRNG;
this.origin = origin; this.bound = bound;
}
-
+
public Spliterator.OfLong trySplit() {
long i = index, m = (i + fence) >>> 1;
- if (m <= i) return null;
- index = m;
- return new RandomLongsSpliterator(generatingRng.split(), i, m, origin, bound);
+ if (m <= i) return null;
+ index = m;
+ return new RandomLongsSpliterator(generatingRNG.split(), i, m, origin, bound);
}
public boolean tryAdvance(LongConsumer consumer) {
if (consumer == null) throw new NullPointerException();
long i = index, f = fence;
if (i < f) {
- consumer.accept(RngSupport.boundedNextLong(generatingRng, origin, bound));
+ consumer.accept(RNGSupport.boundedNextLong(generatingRNG, origin, bound));
index = i + 1;
return true;
}
@@ -273,10 +259,10 @@
long i = index, f = fence;
if (i < f) {
index = f;
- Rng r = generatingRng;
+ RandomNumberGenerator r = generatingRNG;
long o = origin, b = bound;
do {
- consumer.accept(RngSupport.boundedNextLong(r, o, b));
+ consumer.accept(RNGSupport.boundedNextLong(r, o, b));
} while (++i < f);
}
}
@@ -285,29 +271,29 @@
/**
* Spliterator for double streams.
*/
- static class RandomDoublesSpliterator extends RngSupport.RandomSpliterator implements Spliterator.OfDouble {
- final SplittableRng generatingRng;
+ static class RandomDoublesSpliterator extends RNGSupport.RandomSpliterator implements Spliterator.OfDouble {
+ final SplittableRNG generatingRNG;
final double origin;
final double bound;
- RandomDoublesSpliterator(SplittableRng generatingRng, long index, long fence, double origin, double bound) {
- super(index, fence);
- this.generatingRng = generatingRng;
+ RandomDoublesSpliterator(SplittableRNG generatingRNG, long index, long fence, double origin, double bound) {
+ super(index, fence);
+ this.generatingRNG = generatingRNG;
this.origin = origin; this.bound = bound;
}
-
+
public Spliterator.OfDouble trySplit() {
long i = index, m = (i + fence) >>> 1;
- if (m <= i) return null;
- index = m;
- return new RandomDoublesSpliterator(generatingRng.split(), i, m, origin, bound);
+ if (m <= i) return null;
+ index = m;
+ return new RandomDoublesSpliterator(generatingRNG.split(), i, m, origin, bound);
}
public boolean tryAdvance(DoubleConsumer consumer) {
if (consumer == null) throw new NullPointerException();
long i = index, f = fence;
if (i < f) {
- consumer.accept(RngSupport.boundedNextDouble(generatingRng, origin, bound));
+ consumer.accept(RNGSupport.boundedNextDouble(generatingRNG, origin, bound));
index = i + 1;
return true;
}
@@ -319,55 +305,55 @@
long i = index, f = fence;
if (i < f) {
index = f;
- Rng r = generatingRng;
+ RandomNumberGenerator r = generatingRNG;
double o = origin, b = bound;
do {
- consumer.accept(RngSupport.boundedNextDouble(r, o, b));
+ consumer.accept(RNGSupport.boundedNextDouble(r, o, b));
} while (++i < f);
}
}
}
/**
- * Spliterator for stream of generators of type SplittableRng. We multiplex the two
+ * Spliterator for stream of generators of type SplittableRNG. We multiplex the two
* versions into one class by treating "infinite" as equivalent to Long.MAX_VALUE.
* For splits, it uses the standard divide-by-two approach.
*/
- static class RandomSplitsSpliterator extends RngSupport.RandomSpliterator implements Spliterator<SplittableRng> {
- final SplittableRng generatingRng;
- final SplittableRng constructingRng;
+ static class RandomSplitsSpliterator extends RNGSupport.RandomSpliterator implements Spliterator<SplittableRNG> {
+ final SplittableRNG generatingRNG;
+ final SplittableRNG constructingRNG;
- RandomSplitsSpliterator(SplittableRng generatingRng, long index, long fence, SplittableRng constructingRng) {
- super(index, fence);
- this.generatingRng = generatingRng;
- this.constructingRng = constructingRng;
- }
-
- public Spliterator<SplittableRng> trySplit() {
- long i = index, m = (i + fence) >>> 1;
- if (m <= i) return null;
- index = m;
- return new RandomSplitsSpliterator(generatingRng.split(), i, m, constructingRng);
+ RandomSplitsSpliterator(SplittableRNG generatingRNG, long index, long fence, SplittableRNG constructingRNG) {
+ super(index, fence);
+ this.generatingRNG = generatingRNG;
+ this.constructingRNG = constructingRNG;
}
- public boolean tryAdvance(Consumer<? super SplittableRng> consumer) {
+ public Spliterator<SplittableRNG> trySplit() {
+ long i = index, m = (i + fence) >>> 1;
+ if (m <= i) return null;
+ index = m;
+ return new RandomSplitsSpliterator(generatingRNG.split(), i, m, constructingRNG);
+ }
+
+ public boolean tryAdvance(Consumer<? super SplittableRNG> consumer) {
if (consumer == null) throw new NullPointerException();
long i = index, f = fence;
if (i < f) {
- consumer.accept(constructingRng.split(generatingRng));
+ consumer.accept(constructingRNG.split(generatingRNG));
index = i + 1;
return true;
}
else return false;
}
- public void forEachRemaining(Consumer<? super SplittableRng> consumer) {
+ public void forEachRemaining(Consumer<? super SplittableRNG> consumer) {
if (consumer == null) throw new NullPointerException();
long i = index, f = fence;
if (i < f) {
index = f;
- SplittableRng c = constructingRng;
- SplittableRng r = generatingRng;
+ SplittableRNG c = constructingRNG;
+ SplittableRNG r = generatingRNG;
do {
consumer.accept(c.split(r));
} while (++i < f);
--- a/src/java.base/share/classes/java/util/random/ArbitrarilyJumpableRNG.java Thu Jun 27 18:02:51 2019 -0300
+++ b/src/java.base/share/classes/java/util/random/ArbitrarilyJumpableRNG.java Thu Jun 27 18:30:27 2019 -0300
@@ -22,157 +22,141 @@
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
-package java.util;
+
+package java.util.random;
import java.util.stream.Stream;
-import java.util.stream.StreamSupport;
/**
- * This interface is designed to provide a common protocol for objects
- * that generate sequences of pseudorandom numbers (or Boolean values)
- * and furthermore can easily <i>jump</i> to an arbitrarily specified
- * distant point in the state cycle.
- *
- * <p>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 2<sup>127</sup>.
- *
- * <p>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.
+ * This interface is designed to provide a common protocol for objects that generate sequences of
+ * pseudorandom numbers (or Boolean values) and furthermore can easily <i>jump</i> to an arbitrarily
+ * specified distant point in the state cycle.
+ * <p>
+ * Ideally, all {@link ArbitrarilyJumpableRNG} objects produced by iterative jumping from a single
+ * original {@link ArbitrarilyJumpableRNG} 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 2<sup>127</sup>.
+ * <p>
+ * 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 {@link java.math.BigInteger} values as jump distances, {@code double} values are used
+ * instead.
+ * <p>
+ * 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 {@link
+ * 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 {@link ArbitrarilyJumpableRNG}; with care, different jump distances can be used to
+ * traverse the entire state cycle in various ways.
+ * <p>
+ * An implementation of the {@link 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 ArbitrarilyJumpableRNG}, which
+ * provides spliterator-based implementations of the methods {@code ints}, {@code longs}, {@code
+ * doubles}, {@code rngs}, {@code jumps}, and {@code leaps}.
+ * <p>
+ * Objects that implement {@link 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.
*
- * <p>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.
- *
- * <p>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}.
- *
- * <p>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
+ * @since 14
*/
-public interface ArbitrarilyJumpableRng extends LeapableRng {
+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).
+ * 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();
+ ArbitrarilyJumpableRNG copy();
/**
- * Alter the state of this pseudorandom number generator so as to
- * jump forward a distance equal to 2<sup>{@code logDistance}</sup>
- * within its state cycle.
+ * Alter the state of this pseudorandom number generator so as to jump forward a distance equal
+ * to 2<sup>{@code logDistance}</sup> 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<sup>{@code logDistance}</sup> is
- * greater than the period of this generator
+ * @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<sup>{@code logDistance}</sup> 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.
+ * 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
+ *
+ * @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 2<sup>64</sup>
- * or more) within its state cycle. The distance used is that
- * returned by method {@code defaultJumpDistance()}.
+ * Alter the state of this pseudorandom number generator so as to jump forward a large, fixed
+ * distance (typically 2<sup>64</sup> 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)}.
+ * Returns an effectively unlimited stream of new pseudorandom number generators, each of which
+ * implements the {@link ArbitrarilyJumpableRNG} interface, produced by jumping copies of this
+ * generator by different integer multiples of the specified jump distance.
*
* @param distance a distance to jump forward within the state cycle
- * @return a stream of objects that implement the {@code Rng} interface
+ *
+ * @return a stream of objects that implement the {@link RandomNumberGenerator} interface
+ *
+ * @implNote This method is implemented to be equivalent to {@code jumps(Long.MAX_VALUE)}.
*/
- default Stream<ArbitrarilyJumpableRng> jumps(double distance) {
- return Stream.generate(() -> copyAndJump(distance)).sequential();
+ default Stream<ArbitrarilyJumpableRNG> jumps(double distance) {
+ return Stream.generate(() -> copyAndJump(distance)).sequential();
}
/**
- * Returns a stream producing the given {@code streamSize} number 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.
+ * Returns a stream producing the given {@code streamSize} number of new pseudorandom number
+ * generators, each of which implements the {@link ArbitrarilyJumpableRNG} interface, produced
+ * by jumping copies of this generator by different integer multiples of the specified jump
+ * distance.
*
* @param streamSize the number of generators to generate
- * @param distance a distance to jump forward within the state cycle
- * @return a stream of objects that implement the {@code Rng} interface
- * @throws IllegalArgumentException if {@code streamSize} is
- * less than zero
+ * @param distance a distance to jump forward within the state cycle
+ *
+ * @return a stream of objects that implement the {@link RandomNumberGenerator} interface
+ *
+ * @throws IllegalArgumentException if {@code streamSize} is less than zero
*/
- default Stream<ArbitrarilyJumpableRng> jumps(long streamSize, double distance) {
+ default Stream<ArbitrarilyJumpableRNG> jumps(long streamSize, double distance) {
return jumps(distance).limit(streamSize);
}
/**
- * Alter the state of this pseudorandom number generator so as to
- * jump forward a very large, fixed distance (typically 2<sup>128</sup>
- * or more) within its state cycle. The distance used is that
- * returned by method {@code defaultJLeapDistance()}.
+ * Alter the state of this pseudorandom number generator so as to jump forward a very large,
+ * fixed distance (typically 2<sup>128</sup> or more) within its state cycle. The distance used
+ * is that returned by method {@code defaultJLeapDistance()}.
*/
default void leap() { jump(defaultLeapDistance()); }
-
+
/**
* Copy this generator, jump this generator forward, then return the copy.
*
* @param distance a distance to jump forward within the state cycle
+ *
* @return a copy of this generator object before the jump occurred
*/
- default ArbitrarilyJumpableRng copyAndJump(double distance) {
- ArbitrarilyJumpableRng result = copy();
- jump(distance);
- return result;
+ default ArbitrarilyJumpableRNG copyAndJump(double distance) {
+ ArbitrarilyJumpableRNG result = copy();
+ jump(distance);
+ return result;
}
}
--- a/src/java.base/share/classes/java/util/random/DoubleZigguratTables.java Thu Jun 27 18:02:51 2019 -0300
+++ b/src/java.base/share/classes/java/util/random/DoubleZigguratTables.java Thu Jun 27 18:30:27 2019 -0300
@@ -24,7 +24,8 @@
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
-package java.util;
+
+package java.util.random;
class DoubleZigguratTables {
--- a/src/java.base/share/classes/java/util/random/JumpableRNG.java Thu Jun 27 18:02:51 2019 -0300
+++ b/src/java.base/share/classes/java/util/random/JumpableRNG.java Thu Jun 27 18:30:27 2019 -0300
@@ -22,146 +22,128 @@
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
-package java.util;
-import java.math.BigInteger;
+package java.util.random;
+
import java.util.stream.Stream;
/**
- * This interface is designed to provide a common protocol for objects
- * that generate pseudorandom sequences of numbers (or Boolean values)
- * and furthermore can easily <i>jump</i> forward (by a fixed amount)
- * to a distant point in the state cycle.
- *
- * <p>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
- * 2<sup>64</sup> or the square root of its period. Implementors are
- * advised to use algorithms whose period is at least 2<sup>127</sup>.
+ * This interface is designed to provide a common protocol for objects that generate pseudorandom
+ * sequences of numbers (or Boolean values) and furthermore can easily <i>jump</i> forward (by a
+ * fixed amount) to a distant point in the state cycle.
+ * <p>
+ * Ideally, all {@link JumpableRNG} objects produced by iterative jumping from a single original
+ * {@link 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 2<sup>64</sup>
+ * or the square root of its period. Implementors are advised to use algorithms whose period is at
+ * least 2<sup>127</sup>.
+ * <p>
+ * 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 {@link 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<RandomNumberGenerator>} rather than {@code Stream<JumpableRNG>}, even though the actual
+ * generator objects in that stream likely do also implement the {@link JumpableRNG} interface.
+ * <p>
+ * An implementation of the {@link 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.
+ * <p>
+ * Objects that implement {@link 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.
*
- * <p>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<Rng>} rather than {@code Stream<JumpableRng>}, even
- * though the actual generator objects in that stream likely do also
- * implement the {@code JumpableRng} interface.
- *
- * <p>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.
- *
- * <p>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
+ * @since 14
*/
-public interface JumpableRng extends StreamableRng {
+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).
+ * 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();
+ JumpableRNG copy();
/**
- * Alter the state of this pseudorandom number generator so as to
- * jump forward a large, fixed distance (typically 2<sup>64</sup>
- * or more) within its state cycle.
+ * Alter the state of this pseudorandom number generator so as to jump forward a large, fixed
+ * distance (typically 2<sup>64</sup> 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.
+ * 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.
+ * Returns an effectively unlimited stream of new pseudorandom number generators, each of which
+ * implements the {@link RandomNumberGenerator} interface.
*
- * @implNote It is permitted to implement this method in a manner
- * equivalent to {@code jumps(Long.MAX_VALUE)}.
+ * @return a stream of objects that implement the {@link RandomNumberGenerator} interface
*
- * @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
+ * @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.
*/
- default Stream<Rng> jumps() {
- return Stream.generate(this::copyAndJump).sequential();
+ default Stream<RandomNumberGenerator> jumps() {
+ return Stream.generate(this::copyAndJump).sequential();
}
/**
- * Returns a stream producing the given {@code streamSize} number of
- * new pseudorandom number generators, each of which implements the
- * {@code Rng} interface.
- *
- * @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.
+ * Returns a stream producing the given {@code streamSize} number of new pseudorandom number
+ * generators, each of which implements the {@link RandomNumberGenerator} interface.
*
* @param streamSize the number of generators to generate
- * @return a stream of objects that implement the {@code Rng} interface
- * @throws IllegalArgumentException if {@code streamSize} is
- * less than zero
+ *
+ * @return a stream of objects that implement the {@link RandomNumberGenerator} interface
+ *
+ * @throws IllegalArgumentException if {@code streamSize} is less than zero
+ * @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.
*/
- default Stream<Rng> jumps(long streamSize) {
+ default Stream<RandomNumberGenerator> jumps(long streamSize) {
return jumps().limit(streamSize);
}
-
- /**
- * Returns an effectively unlimited stream of new pseudorandom
- * number generators, each of which implements the {@code Rng}
- * interface. Ideally the generators in the stream will appear
- * to be statistically independent.
- *
- * @implNote The default implementation calls {@code jumps()}.
- *
- * @return a stream of objects that implement the {@code Rng} interface
- */
- default Stream<Rng> rngs() {
- return this.jumps();
- }
/**
- * Returns a stream producing the given {@code streamSize} number of
- * new pseudorandom number generators, each of which implements the
- * {@code Rng} interface. Ideally the generators in the stream will
- * appear to be statistically independent.
+ * Returns an effectively unlimited stream of new pseudorandom number generators, each of which
+ * implements the {@link RandomNumberGenerator} interface. Ideally the generators in the stream
+ * will appear to be statistically independent.
+ *
+ * @return a stream of objects that implement the {@link RandomNumberGenerator} interface
*
- * @implNote The default implementation calls {@code jumps(streamSize)}.
+ * @implNote The default implementation calls {@code jumps()}.
+ */
+ default Stream<RandomNumberGenerator> rngs() {
+ return this.jumps();
+ }
+
+ /**
+ * Returns a stream producing the given {@code streamSize} number of new pseudorandom number
+ * generators, each of which implements the {@link RandomNumberGenerator} interface. Ideally
+ * the generators in the stream will appear to be statistically independent.
*
* @param streamSize the number of generators to generate
- * @return a stream of objects that implement the {@code Rng} interface
- * @throws IllegalArgumentException if {@code streamSize} is
- * less than zero
+ *
+ * @return a stream of objects that implement the {@link RandomNumberGenerator} interface
+ *
+ * @throws IllegalArgumentException if {@code streamSize} is less than zero
+ * @implNote The default implementation calls {@code jumps(streamSize)}.
*/
- default Stream<Rng> rngs(long streamSize) {
- return this.jumps(streamSize);
+ default Stream<RandomNumberGenerator> rngs(long streamSize) {
+ return this.jumps(streamSize);
}
/**
@@ -169,10 +151,10 @@
*
* @return a copy of this generator object before the jump occurred
*/
- default Rng copyAndJump() {
- Rng result = copy();
- jump();
- return result;
+ default RandomNumberGenerator copyAndJump() {
+ RandomNumberGenerator result = copy();
+ jump();
+ return result;
}
}
--- a/src/java.base/share/classes/java/util/random/L128X256MixRandom.java Thu Jun 27 18:02:51 2019 -0300
+++ b/src/java.base/share/classes/java/util/random/L128X256MixRandom.java Thu Jun 27 18:30:27 2019 -0300
@@ -22,7 +22,8 @@
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
-package java.util;
+
+package java.util.random;
import java.math.BigInteger;
import java.util.concurrent.atomic.AtomicLong;
@@ -30,14 +31,14 @@
/**
* A generator of uniform pseudorandom values applicable for use in
* (among other contexts) isolated parallel computations that may
- * generate subtasks. Class {@code L128X256MixRandom} implements
- * interfaces {@link java.util.Rng} and {@link java.util.SplittableRng},
+ * generate subtasks. Class {@link L128X256MixRandom} implements
+ * interfaces {@link RandomNumberGenerator} and {@link 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 L128X256MixRandom} objects,
+ * as well as creating new split-off {@link L128X256MixRandom} objects,
* with similar usages as for class {@link java.util.SplittableRandom}.
- *
- * <p>Series of generated values pass the TestU01 BigCrush and PractRand test suites
+ * <p>
+ * 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
* <a href="http://simul.iro.umontreal.ca/testu01/tu01.html">version 1.2.3 of TestU01</a>
@@ -47,56 +48,56 @@
* 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.
- *
- * <p>{@code L128X256MixRandom} is a specific member of the LXM family of algorithms
+ * <p>
+ * {@link 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).
- *
- * <p>The LCG subgenerator for {@code L128X256MixRandom} has an update step of the
+ * (and {@link L128X256MixRandom} does use a mixing function).
+ * <p>
+ * The LCG subgenerator for {@link 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
+ * is fixed (the same for all instances of {@link 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 2<sup>128</sup>); therefore there are 2<sup>127</sup> distinct choices
* of parameter.
- *
- * <p>The Xorshift subgenerator for {@code L128X256MixRandom} is the {@code xoshiro256} algorithm,
+ * <p>
+ * The Xorshift subgenerator for {@link 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 2<sup>256</sup>-1.
- *
- * <p> The mixing function for {@code L128X256MixRandom} is the 64-bit MurmurHash3 finalizer.
- *
- * <p> Because the periods 2<sup>128</sup> and 2<sup>256</sup>-1 of the two subgenerators
- * are relatively prime, the <em>period</em> of any single {@code L128X256MixRandom} object
+ * <p>
+ * The mixing function for {@link L128X256MixRandom} is the 64-bit MurmurHash3 finalizer.
+ * <p>
+ * Because the periods 2<sup>128</sup> and 2<sup>256</sup>-1 of the two subgenerators
+ * are relatively prime, the <em>period</em> of any single {@link 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, 2<sup>128</sup>(2<sup>256</sup>-1),
* which is just slightly smaller than 2<sup>384</sup>. Moreover, if two distinct
- * {@code L128X256MixRandom} objects have different {@code a} parameters, then their
+ * {@link L128X256MixRandom} objects have different {@code a} parameters, then their
* cycles of produced values will be different.
- *
- * <p>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
+ * <p>
+ * The 64-bit values produced by the {@code nextLong()} method are exactly equidistributed.
+ * For any specific instance of {@link L128X256MixRandom}, over the course of its cycle each
* of the 2<sup>64</sup> possible {@code long} values will be produced 2<sup>256</sup>-1 times.
* The values produced by the {@code nextInt()}, {@code nextFloat()}, and {@code nextDouble()}
* methods are likewise exactly equidistributed.
- *
- * <p>In fact, the 64-bit values produced by the {@code nextLong()} method are exactly
- * 2-equidistributed. For any specific instance of {@code L128X256MixRandom}, consider
+ * <p>
+ * In fact, the 64-bit values produced by the {@code nextLong()} method are exactly
+ * 2-equidistributed. For any specific instance of {@link 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 2<sup>128</sup>(2<sup>256</sup>-1) such subsequences, and each subsequence,
* which consists of 2 64-bit values, can have one of 2<sup>128</sup> values, and each
* such value occurs 2<sup>256</sup>-1 times. The values produced by the {@code nextInt()},
* {@code nextFloat()}, and {@code nextDouble()} methods are likewise exactly 2-equidistributed.
- *
- * <p>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
+ * <p>
+ * Moreover, the 64-bit values produced by the {@code nextLong()} method are 4-equidistributed.
+ * To be precise: for any specific instance of {@link 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 <sup>128</sup>(2<sup>256</sup>-1) such subsequences, and each subsequence,
@@ -107,43 +108,42 @@
* 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<sup>-128</sup>.
* (Note that the set of 2<sup>128</sup> less-common subsequence values will differ from
- * one instance of {@code L128X256MixRandom} to another, as a function of the additive
+ * one instance of {@link 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.
- *
- * <p>Method {@link #split} constructs and returns a new {@code L128X256MixRandom}
+ * <p>
+ * Method {@link #split} constructs and returns a new {@link 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
+ * generated by a single thread using a single {@link L128X256MixRandom} object.
+ * This is because, with high probability, distinct {@link 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.
- *
- * <p>As with {@link java.util.SplittableRandom}, instances of
- * {@code L128X256MixRandom} are <em>not</em> thread-safe.
+ * <p>
+ * As with {@link java.util.SplittableRandom}, instances of
+ * {@link L128X256MixRandom} are <em>not</em> 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()}.
- *
- * <p>This class provides additional methods for generating random
+ * <p>
+ * This class provides additional methods for generating random
* streams, that employ the above techniques when used in
* {@code stream.parallel()} mode.
- *
- * <p>Instances of {@code L128X256MixRandom} are not cryptographically
+ * <p>
+ * Instances of {@link 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
+ * @since 14
*/
-public final class L128X256MixRandom extends AbstractSplittableRng {
+public final class L128X256MixRandom extends AbstractSplittableRNG {
/*
* Implementation Overview.
@@ -158,7 +158,7 @@
*
* 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}
+ * that the values generated by two instances of {@link L128X256MixRandom}
* will be (approximately) independent if have different values for `a`.
*
* The default (no-argument) constructor, in essence, uses
@@ -181,13 +181,13 @@
/**
* The seed generator for default constructors.
*/
- private static final AtomicLong defaultGen = new AtomicLong(RngSupport.initialSeed());
+ 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);
+ private static final BigInteger PERIOD =
+ BigInteger.ONE.shiftLeft(256).subtract(BigInteger.ONE).shiftLeft(128);
/*
* The multiplier used in the LCG portion of the algorithm is 2**64 + m;
@@ -205,7 +205,7 @@
* 64-bit arithmetic to work with.
*/
- private static final long m = 2862933555777941757L;
+ private static final long M = 2862933555777941757L;
/* ---------------- instance fields ---------------- */
@@ -238,7 +238,7 @@
* @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.
+ // Force a to be odd.
this.ah = ah;
this.al = al | 1;
this.sh = sh;
@@ -247,67 +247,67 @@
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, 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);
- }
+ // 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
+ * Creates a new instance of {@link L128X256MixRandom} using the
* specified {@code long} value as the initial seed. Instances of
- * {@code L128X256MixRandom} created with the same seed in the same
+ * {@link 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));
+ // 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
+ * Creates a new instance of {@link 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));
+ // 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
+ * Creates a new instance of {@link L128X256MixRandom} using the specified array of
+ * initial seed bytes. Instances of {@link 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.
+ // 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;
@@ -319,29 +319,29 @@
}
/* ---------------- public methods ---------------- */
-
+
/**
- * Constructs and returns a new instance of {@code L128X256MixRandom}
+ * Constructs and returns a new instance of {@link 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
+ * a single {@link 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
+ * @param source a {@link 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}
+ * @return a new instance of {@link 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());
+ 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());
}
/**
@@ -349,19 +349,20 @@
*
* @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
+ 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; }
+ public BigInteger period() {
+ return PERIOD;
+ }
}
--- a/src/java.base/share/classes/java/util/random/L32X64MixRandom.java Thu Jun 27 18:02:51 2019 -0300
+++ b/src/java.base/share/classes/java/util/random/L32X64MixRandom.java Thu Jun 27 18:30:27 2019 -0300
@@ -22,7 +22,8 @@
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
-package java.util;
+
+package java.util.random;
import java.math.BigInteger;
import java.util.concurrent.atomic.AtomicLong;
@@ -30,14 +31,14 @@
/**
* 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},
+ * generate subtasks. Class {@link L32X64MixRandom} implements
+ * interfaces {@link RandomNumberGenerator} and {@link 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,
+ * as well as creating new split-off {@link L32X64MixRandom} objects,
* with similar usages as for class {@link java.util.SplittableRandom}.
- *
- * <p>Series of generated values pass the TestU01 BigCrush and PractRand test suites
+ * <p>
+ * 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
* <a href="http://simul.iro.umontreal.ca/testu01/tu01.html">version 1.2.3 of TestU01</a>
@@ -47,46 +48,46 @@
* 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.
- *
- * <p>{@code L32X64MixRandom} is a specific member of the LXM family of algorithms
+ * <p>
+ * {@link 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).
- *
- * <p>The LCG subgenerator for {@code L32X64MixRandom} has an update step of the
+ * (and {@link L32X64MixRandom} does use a mixing function).
+ * <p>
+ * The LCG subgenerator for {@link 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
+ * is fixed (the same for all instances of {@link 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 2<sup>32</sup>); therefore there are 2<sup>31</sup> distinct choices
* of parameter.
- *
- * <p>The Xorshift subgenerator for {@code L32X64MixRandom} is the {@code xoroshiro64} algorithm,
+ * <p>
+ * The Xorshift subgenerator for {@link 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 2<sup>64</sup>-1.
- *
- * <p> The mixing function for {@code L32X64MixRandom} is the "starstar" mixing function.
- *
- * <p> Because the periods 2<sup>32</sup> and 2<sup>64</sup>-1 of the two subgenerators
- * are relatively prime, the <em>period</em> of any single {@code L32X64MixRandom} object
+ * <p>
+ * The mixing function for {@link L32X64MixRandom} is the "starstar" mixing function.
+ * <p>
+ * Because the periods 2<sup>32</sup> and 2<sup>64</sup>-1 of the two subgenerators
+ * are relatively prime, the <em>period</em> of any single {@link 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, 2<sup>32</sup>(2<sup>64</sup>-1),
* which is just slightly smaller than 2<sup>96</sup>. Moreover, if two distinct
- * {@code L32X64MixRandom} objects have different {@code a} parameters, then their
+ * {@link L32X64MixRandom} objects have different {@code a} parameters, then their
* cycles of produced values will be different.
- *
- * <p>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
+ * <p>
+ * The 32-bit values produced by the {@code nextInt()} method are exactly equidistributed.
+ * For any specific instance of {@link L32X64MixRandom}, over the course of its cycle each
* of the 2<sup>32</sup> possible {@code int} values will be produced 2<sup>64</sup>-1 times.
* The values produced by the {@code nextFloat()} method are likewise exactly equidistributed.
- *
- * <p>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
+ * <p>
+ * In fact, the 32-bit values produced by the {@code nextInt()} method are 2-equidistributed.
+ * To be precise: for any specific instance of {@link 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 2<sup>32</sup>(2<sup>64</sup>-1) such subsequences, and each subsequence,
@@ -97,44 +98,43 @@
* 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<sup>-32</sup>.
* (Note that the set of 2<sup>32</sup> less-common subsequence values will differ from
- * one instance of {@code L32X64MixRandom} to another, as a function of the additive
+ * one instance of {@link 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).
- *
- * <p>Method {@link #split} constructs and returns a new {@code L32X64MixRandom}
+ * <p>
+ * Method {@link #split} constructs and returns a new {@link 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
+ * generated by a single thread using a single {@link L32X64MixRandom} object.
+ * This is because, with high probability, distinct {@link 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.
- *
- * <p>As with {@link java.util.SplittableRandom}, instances of
- * {@code L32X64MixRandom} are <em>not</em> thread-safe.
+ * <p>
+ * As with {@link java.util.SplittableRandom}, instances of
+ * {@link L32X64MixRandom} are <em>not</em> 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()}.
- *
- * <p>This class provides additional methods for generating random
+ * <p>
+ * This class provides additional methods for generating random
* streams, that employ the above techniques when used in
* {@code stream.parallel()} mode.
- *
- * <p>Instances of {@code L32X64MixRandom} are not cryptographically
+ * <p>
+ * Instances of {@link 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
+ * @since 14
*/
-public final class L32X64MixRandom extends AbstractSplittableRng {
+public final class L32X64MixRandom extends AbstractSplittableRNG {
/*
* Implementation Overview.
@@ -145,7 +145,7 @@
*
* 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}
+ * that the values generated by two instances of {@link L32X64MixRandom}
* will be (approximately) independent if have different values for `a`.
*
* The default (no-argument) constructor, in essence, uses
@@ -168,13 +168,13 @@
/**
* The seed generator for default constructors.
*/
- private static final AtomicLong defaultGen = new AtomicLong(RngSupport.initialSeed());
+ 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);
+ private static final BigInteger PERIOD =
+ BigInteger.ONE.shiftLeft(64).subtract(BigInteger.ONE).shiftLeft(32);
/*
* Multiplier used in the LCG portion of the algorithm, taken from
@@ -184,10 +184,10 @@
* Table 4 (third multiplier for size 2<sup>32</sup>).
*/
- private static final int m = 32310901;
+ private static final int M = 32310901;
/* ---------------- instance fields ---------------- */
-
+
/**
* The parameter that is used as an additive constant for the LCG.
* Must be odd.
@@ -213,64 +213,64 @@
* @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.
+ // 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 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);
- }
+ // 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
+ * Creates a new instance of {@link L32X64MixRandom} using the
* specified {@code long} value as the initial seed. Instances of
- * {@code L32X64MixRandom} created with the same seed in the same
+ * {@link 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));
+ // 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
+ * Creates a new instance of {@link 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));
+ // 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
+ * Creates a new instance of {@link L32X64MixRandom} using the specified array of
+ * initial seed bytes. Instances of {@link 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.
+ // 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;
@@ -280,25 +280,23 @@
/* ---------------- 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.
+ * Constructs and returns a new instance of {@link 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 {@link 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}
+ * @param source a {@link 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 {@link L32X64MixRandom}
*/
- public L32X64MixRandom split(SplittableRng source) {
- // Literally pick a new instance "at random".
+ public L32X64MixRandom split(SplittableRNG source) {
+ // Literally pick a new instance "at random".
return new L32X64MixRandom(source.nextInt(), source.nextInt(),
- source.nextInt(), source.nextInt());
+ source.nextInt(), source.nextInt());
}
/**
@@ -307,12 +305,12 @@
* @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
+ 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
}
/**
@@ -320,10 +318,11 @@
*
* @return a pseudorandom {@code long} value
*/
-
public long nextLong() {
- return ((long)(nextInt()) << 32) | nextInt();
+ return ((long)(nextInt()) << 32) | nextInt();
}
- public BigInteger period() { return thePeriod; }
+ public BigInteger period() {
+ return PERIOD;
+ }
}
--- a/src/java.base/share/classes/java/util/random/L64X1024MixRandom.java Thu Jun 27 18:02:51 2019 -0300
+++ b/src/java.base/share/classes/java/util/random/L64X1024MixRandom.java Thu Jun 27 18:30:27 2019 -0300
@@ -22,7 +22,8 @@
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
-package java.util;
+
+package java.util.random;
import java.math.BigInteger;
import java.util.concurrent.atomic.AtomicLong;
@@ -30,14 +31,14 @@
/**
* 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},
+ * generate subtasks. Class {@link L64X1024MixRandom} implements
+ * interfaces {@link RandomNumberGenerator} and {@link 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,
+ * as well as creating new split-off {@link L64X1024MixRandom} objects,
* with similar usages as for class {@link java.util.SplittableRandom}.
- *
- * <p>Series of generated values pass the TestU01 BigCrush and PractRand test suites
+ * <p>
+ * 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
* <a href="http://simul.iro.umontreal.ca/testu01/tu01.html">version 1.2.3 of TestU01</a>
@@ -47,47 +48,47 @@
* 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.
- *
- * <p>{@code L64X1024MixRandom} is a specific member of the LXM family of algorithms
+ * <p>
+ * {@link 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).
- *
- * <p>The LCG subgenerator for {@code L64X1024MixRandom} has an update step of the
+ * (and {@link L64X1024MixRandom} does use a mixing function).
+ * <p>
+ * The LCG subgenerator for {@link 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
+ * is fixed (the same for all instances of {@link 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 2<sup>64</sup>); therefore there are 2<sup>63</sup> distinct choices
* of parameter.
- *
- * <p>The Xorshift subgenerator for {@code L64X1024MixRandom} is the {@code xoroshiro1024}
+ * <p>
+ * The Xorshift subgenerator for {@link 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 2<sup>1024</sup>-1.
- *
- * <p> The mixing function for {@code L64X256MixRandom} is the 64-bit MurmurHash3 finalizer.
- *
- * <p> Because the periods 2<sup>64</sup> and 2<sup>1024</sup>-1 of the two subgenerators
- * are relatively prime, the <em>period</em> of any single {@code L64X1024MixRandom} object
+ * <p>
+ * The mixing function for {@link L64X256MixRandom} is the 64-bit MurmurHash3 finalizer.
+ * <p>
+ * Because the periods 2<sup>64</sup> and 2<sup>1024</sup>-1 of the two subgenerators
+ * are relatively prime, the <em>period</em> of any single {@link 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, 2<sup>64</sup>(2<sup>1024</sup>-1),
* which is just slightly smaller than 2<sup>1088</sup>. Moreover, if two distinct
- * {@code L64X1024MixRandom} objects have different {@code a} parameters, then their
+ * {@link L64X1024MixRandom} objects have different {@code a} parameters, then their
* cycles of produced values will be different.
- *
- * <p>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
+ * <p>
+ * The 64-bit values produced by the {@code nextLong()} method are exactly equidistributed.
+ * For any specific instance of {@link L64X1024MixRandom}, over the course of its cycle each
* of the 2<sup>64</sup> possible {@code long} values will be produced 2<sup>1024</sup>-1 times.
* The values produced by the {@code nextInt()}, {@code nextFloat()}, and {@code nextDouble()}
* methods are likewise exactly equidistributed.
- *
- * <p>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
+ * <p>
+ * In fact, the 64-bit values produced by the {@code nextLong()} method are 16-equidistributed.
+ * To be precise: for any specific instance of {@link 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 2<sup>64</sup>(2<sup>1024</sup>-1) such subsequences, and each subsequence,
@@ -98,43 +99,42 @@
* 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<sup>-64</sup>.
* (Note that the set of 2<sup>64</sup> less-common subsequence values will differ from
- * one instance of {@code L64X1024MixRandom} to another, as a function of the additive
+ * one instance of {@link 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.
- *
- * <p>Method {@link #split} constructs and returns a new {@code L64X1024MixRandom}
+ * <p>
+ * Method {@link #split} constructs and returns a new {@link 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
+ * generated by a single thread using a single {@link L64X1024MixRandom} object.
+ * This is because, with high probability, distinct {@link 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.
- *
- * <p>As with {@link java.util.SplittableRandom}, instances of
- * {@code L64X1024MixRandom} are <em>not</em> thread-safe.
+ * <p>
+ * As with {@link java.util.SplittableRandom}, instances of
+ * {@link L64X1024MixRandom} are <em>not</em> 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()}.
- *
- * <p>This class provides additional methods for generating random
+ * <p>
+ * This class provides additional methods for generating random
* streams, that employ the above techniques when used in
* {@code stream.parallel()} mode.
- *
- * <p>Instances of {@code L64X1024MixRandom} are not cryptographically
+ * <p>
+ * Instances of {@link 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
+ * @since 14
*/
-public final class L64X1024MixRandom extends AbstractSplittableRng {
+public final class L64X1024MixRandom extends AbstractSplittableRNG {
/*
* Implementation Overview.
@@ -145,7 +145,7 @@
*
* 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}
+ * that the values generated by two instances of {@link L64X1024MixRandom}
* will be (approximately) independent if have different values for `a`.
*
* The default (no-argument) constructor, in essence, uses
@@ -174,13 +174,13 @@
/**
* The seed generator for default constructors.
*/
- private static final AtomicLong defaultGen = new AtomicLong(RngSupport.initialSeed());
+ 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);
+ private static final BigInteger PERIOD =
+ BigInteger.ONE.shiftLeft(N*64).subtract(BigInteger.ONE).shiftLeft(64);
/*
* Multiplier used in the LCG portion of the algorithm, taken from
@@ -190,8 +190,8 @@
* Table 4 (first multiplier for size 2<sup>64</sup>).
*/
- private static final long m = 2862933555777941757L;
-
+ private static final long M = 2862933555777941757L;
+
/* ---------------- instance fields ---------------- */
/**
@@ -236,16 +236,16 @@
* @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.
+ 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 = new long[N];
+ this.x[0] = x0;
+ this.x[1] = x1;
this.x[2] = x2;
this.x[3] = x3;
this.x[4] = x4;
@@ -260,113 +260,113 @@
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, ..., 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);
- }
- }
+ // 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
+ * Creates a new instance of {@link L64X1024MixRandom} using the
* specified {@code long} value as the initial seed. Instances of
- * {@code L64X1024MixRandom} created with the same seed in the same
+ * {@link 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));
+ // 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
+ * Creates a new instance of {@link 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));
+ // 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
+ * Creates a new instance of {@link L64X1024MixRandom} using the specified array of
+ * initial seed bytes. Instances of {@link 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.
+ // 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];
- }
+ 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}
+ * Constructs and returns a new instance of {@link 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
+ * a single {@link 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
+ * @param source a {@link 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}
+ * @return a new instance of {@link 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());
+ 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());
}
/**
@@ -374,23 +374,24 @@
*
* @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];
+ // 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
+ 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
+ // 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; }
+ public BigInteger period() {
+ return PERIOD;
+ }
}
--- a/src/java.base/share/classes/java/util/random/L64X1024Random.java Thu Jun 27 18:02:51 2019 -0300
+++ b/src/java.base/share/classes/java/util/random/L64X1024Random.java Thu Jun 27 18:30:27 2019 -0300
@@ -22,7 +22,8 @@
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
-package java.util;
+
+package java.util.random;
import java.math.BigInteger;
import java.util.concurrent.atomic.AtomicLong;
@@ -30,14 +31,14 @@
/**
* 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},
+ * generate subtasks. Class {@link L64X1024Random} implements
+ * interfaces {@link RandomNumberGenerator} and {@link 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,
+ * as well as creating new split-off {@link L64X1024Random} objects,
* with similar usages as for class {@link java.util.SplittableRandom}.
- *
- * <p>Series of generated values pass the TestU01 BigCrush and PractRand test suites
+ * <p>
+ * 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
* <a href="http://simul.iro.umontreal.ca/testu01/tu01.html">version 1.2.3 of TestU01</a>
@@ -47,45 +48,45 @@
* 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.
- *
- * <p>{@code L64X1024Random} is a specific member of the LXM family of algorithms
+ * <p>
+ * {@link 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).
- *
- * <p>The LCG subgenerator for {@code L64X1024Random} has an update step of the
+ * (but {@link L64X1024Random} does not use a mixing function).
+ * <p>
+ * The LCG subgenerator for {@link 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
+ * is fixed (the same for all instances of {@link 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 2<sup>64</sup>); therefore there are 2<sup>63</sup> distinct choices
* of parameter.
- *
- * <p>The Xorshift subgenerator for {@code L64X1024Random} is the {@code xoroshiro1024}
+ * <p>
+ * The Xorshift subgenerator for {@link 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 2<sup>1024</sup>-1.
- *
- * <p> Because the periods 2<sup>64</sup> and 2<sup>1024</sup>-1 of the two subgenerators
- * are relatively prime, the <em>period</em> of any single {@code L64X1024Random} object
+ * <p>
+ * Because the periods 2<sup>64</sup> and 2<sup>1024</sup>-1 of the two subgenerators
+ * are relatively prime, the <em>period</em> of any single {@link 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, 2<sup>64</sup>(2<sup>1024</sup>-1),
* which is just slightly smaller than 2<sup>1088</sup>. Moreover, if two distinct
- * {@code L64X1024Random} objects have different {@code a} parameters, then their
+ * {@link L64X1024Random} objects have different {@code a} parameters, then their
* cycles of produced values will be different.
- *
- * <p>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
+ * <p>
+ * The 64-bit values produced by the {@code nextLong()} method are exactly equidistributed.
+ * For any specific instance of {@link L64X1024Random}, over the course of its cycle each
* of the 2<sup>64</sup> possible {@code long} values will be produced 2<sup>1024</sup>-1 times.
* The values produced by the {@code nextInt()}, {@code nextFloat()}, and {@code nextDouble()}
* methods are likewise exactly equidistributed.
- *
- * <p>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
+ * <p>
+ * In fact, the 64-bit values produced by the {@code nextLong()} method are 16-equidistributed.
+ * To be precise: for any specific instance of {@link 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 2<sup>64</sup>(2<sup>1024</sup>-1) such subsequences, and each subsequence,
@@ -96,43 +97,42 @@
* 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<sup>-64</sup>.
* (Note that the set of 2<sup>64</sup> less-common subsequence values will differ from
- * one instance of {@code L64X1024Random} to another, as a function of the additive
+ * one instance of {@link 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.
- *
- * <p>Method {@link #split} constructs and returns a new {@code L64X1024Random}
+ * <p>
+ * Method {@link #split} constructs and returns a new {@link 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
+ * generated by a single thread using a single {@link L64X1024Random} object.
+ * This is because, with high probability, distinct {@link 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.
- *
- * <p>As with {@link java.util.SplittableRandom}, instances of
- * {@code L64X1024Random} are <em>not</em> thread-safe.
+ * <p>
+ * As with {@link java.util.SplittableRandom}, instances of
+ * {@link L64X1024Random} are <em>not</em> 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()}.
- *
- * <p>This class provides additional methods for generating random
+ * <p>
+ * This class provides additional methods for generating random
* streams, that employ the above techniques when used in
* {@code stream.parallel()} mode.
- *
- * <p>Instances of {@code L64X1024Random} are not cryptographically
+ * <p>
+ * Instances of {@link 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
+ * @since 14
*/
-public final class L64X1024Random extends AbstractSplittableRng {
+public final class L64X1024Random extends AbstractSplittableRNG {
/*
* Implementation Overview.
@@ -143,7 +143,7 @@
*
* 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}
+ * that the values generated by two instances of {@link L64X1024Random}
* will be (approximately) independent if have different values for `a`.
*
* The default (no-argument) constructor, in essence, uses
@@ -172,13 +172,13 @@
/**
* The seed generator for default constructors.
*/
- private static final AtomicLong defaultGen = new AtomicLong(RngSupport.initialSeed());
+ 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);
+ private static final BigInteger PERIOD =
+ BigInteger.ONE.shiftLeft(N*64).subtract(BigInteger.ONE).shiftLeft(64);
/*
* Multiplier used in the LCG portion of the algorithm, taken from
@@ -188,8 +188,8 @@
* Table 4 (first multiplier for size 2<sup>64</sup>).
*/
- private static final long m = 2862933555777941757L;
-
+ private static final long M = 2862933555777941757L;
+
/* ---------------- instance fields ---------------- */
/**
@@ -234,16 +234,16 @@
* @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.
+ 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 = new long[N];
+ this.x[0] = x0;
+ this.x[1] = x1;
this.x[2] = x2;
this.x[3] = x3;
this.x[4] = x4;
@@ -258,112 +258,112 @@
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, ..., 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);
- }
- }
+ 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
+ * Creates a new instance of {@link L64X1024Random} using the
* specified {@code long} value as the initial seed. Instances of
- * {@code L64X1024Random} created with the same seed in the same
+ * {@link 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));
+ // 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
+ * Creates a new instance of {@link 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));
+ // 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
+ * Creates a new instance of {@link L64X1024Random} using the specified array of
+ * initial seed bytes. Instances of {@link 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.
+ // 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];
- }
+ 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}
+ * Constructs and returns a new instance of {@link 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
+ * a single {@link 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
+ * @param source a {@link 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}
+ * @return a new instance of {@link 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());
+ 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());
}
/**
@@ -371,23 +371,24 @@
*
* @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];
+ // 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
+ 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;
+ // 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; }
+ public BigInteger period() {
+ return PERIOD;
+ }
}
--- a/src/java.base/share/classes/java/util/random/L64X128MixRandom.java Thu Jun 27 18:02:51 2019 -0300
+++ b/src/java.base/share/classes/java/util/random/L64X128MixRandom.java Thu Jun 27 18:30:27 2019 -0300
@@ -22,7 +22,8 @@
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
-package java.util;
+
+package java.util.random;
import java.math.BigInteger;
import java.util.concurrent.atomic.AtomicLong;
@@ -30,14 +31,14 @@
/**
* 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},
+ * generate subtasks. Class {@link L64X128MixRandom} implements
+ * interfaces {@link RandomNumberGenerator} and {@link 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,
+ * as well as creating new split-off {@link L64X128MixRandom} objects,
* with similar usages as for class {@link java.util.SplittableRandom}.
- *
- * <p>Series of generated values pass the TestU01 BigCrush and PractRand test suites
+ * <p>
+ * 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
* <a href="http://simul.iro.umontreal.ca/testu01/tu01.html">version 1.2.3 of TestU01</a>
@@ -47,47 +48,47 @@
* 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.
- *
- * <p>{@code L64X128MixRandom} is a specific member of the LXM family of algorithms
+ * <p>
+ * {@link 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).
- *
- * <p>The LCG subgenerator for {@code L64X128MixRandom} has an update step of the
+ * (and {@link L64X128MixRandom} does use a mixing function).
+ * <p>
+ * The LCG subgenerator for {@link 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
+ * is fixed (the same for all instances of {@link 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 2<sup>64</sup>); therefore there are 2<sup>63</sup> distinct choices
* of parameter.
- *
- * <p>The Xorshift subgenerator for {@code L64X128MixRandom} is the {@code xoroshiro128} algorithm,
+ * <p>
+ * The Xorshift subgenerator for {@link 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 2<sup>128</sup>-1.
- *
- * <p> The mixing function for {@code L64X128MixRandom} is the 64-bit "starstar(5,7,9)" function.
- *
- * <p> Because the periods 2<sup>64</sup> and 2<sup>128</sup>-1 of the two subgenerators
- * are relatively prime, the <em>period</em> of any single {@code L64X128MixRandom} object
+ * <p>
+ * The mixing function for {@link L64X128MixRandom} is the 64-bit "starstar(5,7,9)" function.
+ * <p>
+ * Because the periods 2<sup>64</sup> and 2<sup>128</sup>-1 of the two subgenerators
+ * are relatively prime, the <em>period</em> of any single {@link 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, 2<sup>64</sup>(2<sup>128</sup>-1),
* which is just slightly smaller than 2<sup>192</sup>. Moreover, if two distinct
- * {@code L64X128MixRandom} objects have different {@code a} parameters, then their
+ * {@link L64X128MixRandom} objects have different {@code a} parameters, then their
* cycles of produced values will be different.
- *
- * <p>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
+ * <p>
+ * The 64-bit values produced by the {@code nextLong()} method are exactly equidistributed.
+ * For any specific instance of {@link L64X128MixRandom}, over the course of its cycle each
* of the 2<sup>64</sup> possible {@code long} values will be produced 2<sup>128</sup>-1 times.
* The values produced by the {@code nextInt()}, {@code nextFloat()}, and {@code nextDouble()}
* methods are likewise exactly equidistributed.
- *
- * <p>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
+ * <p>
+ * In fact, the 64-bit values produced by the {@code nextLong()} method are 2-equidistributed.
+ * To be precise: for any specific instance of {@link 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 2<sup>64</sup>(2<sup>128</sup>-1) such subsequences, and each subsequence,
@@ -98,43 +99,42 @@
* 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<sup>-64</sup>.
* (Note that the set of 2<sup>64</sup> less-common subsequence values will differ from
- * one instance of {@code L64X128MixRandom} to another, as a function of the additive
+ * one instance of {@link 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.
- *
- * <p>Method {@link #split} constructs and returns a new {@code L64X128MixRandom}
+ * <p>
+ * Method {@link #split} constructs and returns a new {@link 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
+ * generated by a single thread using a single {@link L64X128MixRandom} object.
+ * This is because, with high probability, distinct {@link 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.
- *
- * <p>As with {@link java.util.SplittableRandom}, instances of
- * {@code L64X128MixRandom} are <em>not</em> thread-safe.
+ * <p>
+ * As with {@link java.util.SplittableRandom}, instances of
+ * {@link L64X128MixRandom} are <em>not</em> 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()}.
- *
- * <p>This class provides additional methods for generating random
+ * <p>
+ * This class provides additional methods for generating random
* streams, that employ the above techniques when used in
* {@code stream.parallel()} mode.
- *
- * <p>Instances of {@code L64X128MixRandom} are not cryptographically
+ * <p>
+ * Instances of {@link 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
+ * @since 14
*/
-public final class L64X128MixRandom extends AbstractSplittableRng {
+public final class L64X128MixRandom extends AbstractSplittableRNG {
/*
* Implementation Overview.
@@ -145,7 +145,7 @@
*
* 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}
+ * that the values generated by two instances of {@link L64X128MixRandom}
* will be (approximately) independent if have different values for `a`.
*
* The default (no-argument) constructor, in essence, uses
@@ -162,19 +162,19 @@
* 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());
+ 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);
+ private static final BigInteger PERIOD =
+ BigInteger.ONE.shiftLeft(128).subtract(BigInteger.ONE).shiftLeft(64);
/*
* Multiplier used in the LCG portion of the algorithm, taken from
@@ -184,7 +184,7 @@
* Table 4 (first multiplier for size 2<sup>64</sup>).
*/
- private static final long m = 2862933555777941757L;
+ private static final long M = 2862933555777941757L;
/* ---------------- instance fields ---------------- */
@@ -213,66 +213,66 @@
* @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.
+ // Force a to be odd.
this.a = a | 1;
this.s = s;
- this.x0 = x0;
+ this.x0 = x0;
this.x1 = x1;
- // If x0 and x1 are both zero, we must choose nonzero values.
+ // 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);
- }
+ // 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
+ * Creates a new instance of {@link L64X128MixRandom} using the
* specified {@code long} value as the initial seed. Instances of
- * {@code L64X128MixRandom} created with the same seed in the same
+ * {@link 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));
+ // 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
+ * Creates a new instance of {@link 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));
+ // 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
+ * Creates a new instance of {@link L64X128MixRandom} using the specified array of
+ * initial seed bytes. Instances of {@link 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.
+ // 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;
@@ -280,27 +280,28 @@
}
/* ---------------- public methods ---------------- */
-
+
/**
- * Constructs and returns a new instance of {@code L64X128MixRandom}
+ * Constructs and returns a new instance of {@link 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
+ * a single {@link 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
+ * @param source a {@link 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}
+ *
+ * @return a new instance of {@link L64X128MixRandom}
*/
- public L64X128MixRandom split(SplittableRng source) {
- // Literally pick a new instance "at random".
+ public L64X128MixRandom split(SplittableRNG source) {
+ // Literally pick a new instance "at random".
return new L64X128MixRandom(source.nextLong(), source.nextLong(),
- source.nextLong(), source.nextLong());
+ source.nextLong(), source.nextLong());
}
/**
@@ -308,15 +309,16 @@
*
* @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
+ 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; }
+ public BigInteger period() {
+ return PERIOD;
+ }
}
--- a/src/java.base/share/classes/java/util/random/L64X128Random.java Thu Jun 27 18:02:51 2019 -0300
+++ b/src/java.base/share/classes/java/util/random/L64X128Random.java Thu Jun 27 18:30:27 2019 -0300
@@ -22,7 +22,8 @@
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
-package java.util;
+
+package java.util.random;
import java.math.BigInteger;
import java.util.concurrent.atomic.AtomicLong;
@@ -30,14 +31,14 @@
/**
* 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},
+ * generate subtasks. Class {@link L64X128Random} implements
+ * interfaces {@link RandomNumberGenerator} and {@link 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,
+ * as well as creating new split-off {@link L64X128Random} objects,
* with similar usages as for class {@link java.util.SplittableRandom}.
- *
- * <p>Series of generated values pass the TestU01 BigCrush and PractRand test suites
+ * <p>
+ * 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
* <a href="http://simul.iro.umontreal.ca/testu01/tu01.html">version 1.2.3 of TestU01</a>
@@ -47,45 +48,45 @@
* 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.
- *
- * <p>{@code L64X128Random} is a specific member of the LXM family of algorithms
+ * <p>
+ * {@link 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).
- *
- * <p>The LCG subgenerator for {@code L64X128Random} has an update step of the
+ * (but {@link L64X128Random} does not use a mixing function).
+ * <p>
+ * The LCG subgenerator for {@link 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
+ * is fixed (the same for all instances of {@link 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 2<sup>64</sup>); therefore there are 2<sup>63</sup> distinct choices
* of parameter.
- *
- * <p>The Xorshift subgenerator for {@code L64X128Random} is the {@code xoroshiro128} algorithm,
+ * <p>
+ * The Xorshift subgenerator for {@link 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 2<sup>128</sup>-1.
- *
- * <p> Because the periods 2<sup>64</sup> and 2<sup>128</sup>-1 of the two subgenerators
- * are relatively prime, the <em>period</em> of any single {@code L64X128Random} object
+ * <p>
+ * Because the periods 2<sup>64</sup> and 2<sup>128</sup>-1 of the two subgenerators
+ * are relatively prime, the <em>period</em> of any single {@link 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, 2<sup>64</sup>(2<sup>128</sup>-1),
* which is just slightly smaller than 2<sup>192</sup>. Moreover, if two distinct
- * {@code L64X128Random} objects have different {@code a} parameters, then their
+ * {@link L64X128Random} objects have different {@code a} parameters, then their
* cycles of produced values will be different.
- *
- * <p>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
+ * <p>
+ * The 64-bit values produced by the {@code nextLong()} method are exactly equidistributed.
+ * For any specific instance of {@link L64X128Random}, over the course of its cycle each
* of the 2<sup>64</sup> possible {@code long} values will be produced 2<sup>128</sup>-1 times.
* The values produced by the {@code nextInt()}, {@code nextFloat()}, and {@code nextDouble()}
* methods are likewise exactly equidistributed.
- *
- * <p>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
+ * <p>
+ * In fact, the 64-bit values produced by the {@code nextLong()} method are 2-equidistributed.
+ * To be precise: for any specific instance of {@link 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 2<sup>64</sup>(2<sup>128</sup>-1) such subsequences, and each subsequence,
@@ -96,43 +97,42 @@
* 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<sup>-64</sup>.
* (Note that the set of 2<sup>64</sup> less-common subsequence values will differ from
- * one instance of {@code L64X128Random} to another, as a function of the additive
+ * one instance of {@link 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.
- *
- * <p>Method {@link #split} constructs and returns a new {@code L64X128Random}
+ * <p>
+ * Method {@link #split} constructs and returns a new {@link 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
+ * generated by a single thread using a single {@link L64X128Random} object.
+ * This is because, with high probability, distinct {@link 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.
- *
- * <p>As with {@link java.util.SplittableRandom}, instances of
- * {@code L64X128Random} are <em>not</em> thread-safe.
+ * <p>
+ * As with {@link java.util.SplittableRandom}, instances of
+ * {@link L64X128Random} are <em>not</em> 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()}.
- *
- * <p>This class provides additional methods for generating random
+ * <p>
+ * This class provides additional methods for generating random
* streams, that employ the above techniques when used in
* {@code stream.parallel()} mode.
- *
- * <p>Instances of {@code L64X128Random} are not cryptographically
+ * <p>
+ * Instances of {@link 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
+ * @since 14
*/
-public final class L64X128Random extends AbstractSplittableRng {
+public final class L64X128Random extends AbstractSplittableRNG {
/*
* Implementation Overview.
@@ -143,7 +143,7 @@
*
* 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}
+ * that the values generated by two instances of {@link L64X128Random}
* will be (approximately) independent if have different values for `a`.
*
* The default (no-argument) constructor, in essence, uses
@@ -166,13 +166,13 @@
/**
* The seed generator for default constructors.
*/
- private static final AtomicLong defaultGen = new AtomicLong(RngSupport.initialSeed());
-
+ 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);
+ private static final BigInteger PERIOD =
+ BigInteger.ONE.shiftLeft(128).subtract(BigInteger.ONE).shiftLeft(64);
/*
* Multiplier used in the LCG portion of the algorithm, taken from
@@ -182,7 +182,7 @@
* Table 4 (first multiplier for size 2<sup>64</sup>).
*/
- private static final long m = 2862933555777941757L;
+ private static final long M = 2862933555777941757L;
/* ---------------- instance fields ---------------- */
@@ -211,64 +211,64 @@
* @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.
+ // 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 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);
- }
+ // 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
+ * Creates a new instance of {@link L64X128Random} using the
* specified {@code long} value as the initial seed. Instances of
- * {@code L64X128Random} created with the same seed in the same
+ * {@link 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));
+ // 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
+ * Creates a new instance of {@link 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));
+ // 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
+ * Creates a new instance of {@link L64X128MixRandom} using the specified array of
+ * initial seed bytes. Instances of {@link 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.
+ // 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;
@@ -278,25 +278,26 @@
/* ---------------- public methods ---------------- */
/**
- * Constructs and returns a new instance of {@code L64X128Random}
+ * Constructs and returns a new instance of {@link 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
+ * a single {@link 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
+ * @param source a {@link 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}
+ *
+ * @return a new instance of {@link L64X128Random}
*/
- public L64X128Random split(SplittableRng source) {
- // Literally pick a new instance "at random".
+ public L64X128Random split(SplittableRNG source) {
+ // Literally pick a new instance "at random".
return new L64X128Random(source.nextLong(), source.nextLong(),
- source.nextLong(), source.nextLong());
+ source.nextLong(), source.nextLong());
}
/**
@@ -304,15 +305,16 @@
*
* @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;
+ 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; }
+ public BigInteger period() {
+ return PERIOD;
+ }
}
--- a/src/java.base/share/classes/java/util/random/L64X256MixRandom.java Thu Jun 27 18:02:51 2019 -0300
+++ b/src/java.base/share/classes/java/util/random/L64X256MixRandom.java Thu Jun 27 18:30:27 2019 -0300
@@ -22,7 +22,8 @@
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
-package java.util;
+
+package java.util.random;
import java.math.BigInteger;
import java.util.concurrent.atomic.AtomicLong;
@@ -30,14 +31,14 @@
/**
* 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},
+ * generate subtasks. Class {@link L64X256MixRandom} implements
+ * interfaces {@link RandomNumberGenerator} and {@link 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,
+ * as well as creating new split-off {@link L64X256MixRandom} objects,
* with similar usages as for class {@link java.util.SplittableRandom}.
- *
- * <p>Series of generated values pass the TestU01 BigCrush and PractRand test suites
+ * <p>
+ * 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
* <a href="http://simul.iro.umontreal.ca/testu01/tu01.html">version 1.2.3 of TestU01</a>
@@ -47,47 +48,47 @@
* 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.
- *
- * <p>{@code L64X256MixRandom} is a specific member of the LXM family of algorithms
+ * <p>
+ * {@link 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).
- *
- * <p>The LCG subgenerator for {@code L64X256MixRandom} has an update step of the
+ * (and {@link L64X256MixRandom} does use a mixing function).
+ * <p>
+ * The LCG subgenerator for {@link 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
+ * is fixed (the same for all instances of {@link 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 2<sup>64</sup>); therefore there are 2<sup>63</sup> distinct choices
* of parameter.
- *
- * <p>The Xorshift subgenerator for {@code L64X256MixRandom} is the {@code xoshiro256} algorithm,
+ * <p>
+ * The Xorshift subgenerator for {@link 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 2<sup>256</sup>-1.
- *
- * <p> The mixing function for {@code L64X256MixRandom} is the 64-bit MurmurHash3 finalizer.
- *
- * <p> Because the periods 2<sup>64</sup> and 2<sup>256</sup>-1 of the two subgenerators
- * are relatively prime, the <em>period</em> of any single {@code L64X256MixRandom} object
+ * <p>
+ * The mixing function for {@link L64X256MixRandom} is the 64-bit MurmurHash3 finalizer.
+ * <p>
+ * Because the periods 2<sup>64</sup> and 2<sup>256</sup>-1 of the two subgenerators
+ * are relatively prime, the <em>period</em> of any single {@link 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, 2<sup>64</sup>(2<sup>256</sup>-1),
* which is just slightly smaller than 2<sup>320</sup>. Moreover, if two distinct
- * {@code L64X256MixRandom} objects have different {@code a} parameters, then their
+ * {@link L64X256MixRandom} objects have different {@code a} parameters, then their
* cycles of produced values will be different.
- *
- * <p>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
+ * <p>
+ * The 64-bit values produced by the {@code nextLong()} method are exactly equidistributed.
+ * For any specific instance of {@link L64X256MixRandom}, over the course of its cycle each
* of the 2<sup>64</sup> possible {@code long} values will be produced 2<sup>256</sup>-1 times.
* The values produced by the {@code nextInt()}, {@code nextFloat()}, and {@code nextDouble()}
* methods are likewise exactly equidistributed.
- *
- * <p>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
+ * <p>
+ * In fact, the 64-bit values produced by the {@code nextLong()} method are 4-equidistributed.
+ * To be precise: for any specific instance of {@link 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 2<sup>64</sup>(2<sup>256</sup>-1) such subsequences, and each subsequence,
@@ -98,43 +99,42 @@
* 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<sup>-64</sup>.
* (Note that the set of 2<sup>64</sup> less-common subsequence values will differ from
- * one instance of {@code L64X256MixRandom} to another, as a function of the additive
+ * one instance of {@link 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.
- *
- * <p>Method {@link #split} constructs and returns a new {@code L64X256MixRandom}
+ * <p>
+ * Method {@link #split} constructs and returns a new {@link 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
+ * generated by a single thread using a single {@link L64X256MixRandom} object.
+ * This is because, with high probability, distinct {@link 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.
- *
- * <p>As with {@link java.util.SplittableRandom}, instances of
- * {@code L64X256MixRandom} are <em>not</em> thread-safe.
+ * <p>
+ * As with {@link java.util.SplittableRandom}, instances of
+ * {@link L64X256MixRandom} are <em>not</em> 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()}.
- *
- * <p>This class provides additional methods for generating random
+ * <p>
+ * This class provides additional methods for generating random
* streams, that employ the above techniques when used in
* {@code stream.parallel()} mode.
- *
- * <p>Instances of {@code L64X256MixRandom} are not cryptographically
+ * <p>
+ * Instances of {@link 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
+ * @since 14
*/
-public final class L64X256MixRandom extends AbstractSplittableRng {
+public final class L64X256MixRandom extends AbstractSplittableRNG {
/*
* Implementation Overview.
@@ -146,7 +146,7 @@
*
* 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}
+ * that the values generated by two instances of {@link L64X256MixRandom}
* will be (approximately) independent if have different values for `a`.
*
* The default (no-argument) constructor, in essence, uses
@@ -169,13 +169,13 @@
/**
* The seed generator for default constructors.
*/
- private static final AtomicLong defaultGen = new AtomicLong(RngSupport.initialSeed());
+ 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);
+ private static final BigInteger PERIOD =
+ BigInteger.ONE.shiftLeft(256).subtract(BigInteger.ONE).shiftLeft(64);
/*
* Multiplier used in the LCG portion of the algorithm, taken from
@@ -185,7 +185,7 @@
* Table 4 (first multiplier for size 2<sup>64</sup>).
*/
- private static final long m = 2862933555777941757L;
+ private static final long M = 2862933555777941757L;
/* ---------------- instance fields ---------------- */
@@ -216,72 +216,72 @@
* @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.
+ // 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, 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);
- }
+ // 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
+ * Creates a new instance of {@link L64X256MixRandom} using the
* specified {@code long} value as the initial seed. Instances of
- * {@code L64X256MixRandom} created with the same seed in the same
+ * {@link 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));
+ // 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
+ * Creates a new instance of {@link 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));
+ // 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
+ * Creates a new instance of {@link L64X256MixRandom} using the specified array of
+ * initial seed bytes. Instances of {@link 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.
+ // 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;
@@ -291,28 +291,29 @@
}
/* ---------------- public methods ---------------- */
-
+
/**
- * Constructs and returns a new instance of {@code L64X256MixRandom}
+ * Constructs and returns a new instance of {@link 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
+ * a single {@link 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
+ * @param source a {@link 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}
+ *
+ * @return a new instance of {@link 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());
+ 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());
}
/**
@@ -320,15 +321,16 @@
*
* @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
+ 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; }
+ public BigInteger period() {
+ return PERIOD;
+ }
}
--- a/src/java.base/share/classes/java/util/random/L64X256Random.java Thu Jun 27 18:02:51 2019 -0300
+++ b/src/java.base/share/classes/java/util/random/L64X256Random.java Thu Jun 27 18:30:27 2019 -0300
@@ -22,7 +22,8 @@
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
-package java.util;
+
+package java.util.random;
import java.math.BigInteger;
import java.util.concurrent.atomic.AtomicLong;
@@ -30,14 +31,14 @@
/**
* 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},
+ * generate subtasks. Class {@link L64X256Random} implements
+ * interfaces {@link RandomNumberGenerator} and {@link 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,
+ * as well as creating new split-off {@link L64X256Random} objects,
* with similar usages as for class {@link java.util.SplittableRandom}.
- *
- * <p>Series of generated values pass the TestU01 BigCrush and PractRand test suites
+ * <p>
+ * 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
* <a href="http://simul.iro.umontreal.ca/testu01/tu01.html">version 1.2.3 of TestU01</a>
@@ -47,45 +48,45 @@
* 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.
- *
- * <p>{@code L64X256Random} is a specific member of the LXM family of algorithms
+ * <p>
+ * {@link 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).
- *
- * <p>The LCG subgenerator for {@code L64X256Random} has an update step of the
+ * (but {@link L64X256Random} does not use a mixing function).
+ * <p>
+ * The LCG subgenerator for {@link 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
+ * is fixed (the same for all instances of {@link 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 2<sup>64</sup>); therefore there are 2<sup>63</sup> distinct choices
* of parameter.
- *
- * <p>The Xorshift subgenerator for {@code L64X256Random} is the {@code xoshiro256} algorithm,
+ * <p>
+ * The Xorshift subgenerator for {@link 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 2<sup>256</sup>-1.
- *
- * <p> Because the periods 2<sup>64</sup> and 2<sup>256</sup>-1 of the two subgenerators
- * are relatively prime, the <em>period</em> of any single {@code L64X256Random} object
+ * <p>
+ * Because the periods 2<sup>64</sup> and 2<sup>256</sup>-1 of the two subgenerators
+ * are relatively prime, the <em>period</em> of any single {@link 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, 2<sup>64</sup>(2<sup>256</sup>-1),
* which is just slightly smaller than 2<sup>320</sup>. Moreover, if two distinct
- * {@code L64X256Random} objects have different {@code a} parameters, then their
+ * {@link L64X256Random} objects have different {@code a} parameters, then their
* cycles of produced values will be different.
- *
- * <p>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
+ * <p>
+ * The 64-bit values produced by the {@code nextLong()} method are exactly equidistributed.
+ * For any specific instance of {@link L64X256Random}, over the course of its cycle each
* of the 2<sup>64</sup> possible {@code long} values will be produced 2<sup>256</sup>-1 times.
* The values produced by the {@code nextInt()}, {@code nextFloat()}, and {@code nextDouble()}
* methods are likewise exactly equidistributed.
- *
- * <p> 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
+ * <p>
+ * In fact, the 64-bit values produced by the {@code nextLong()} method are 4-equidistributed.
+ * To be precise: for any specific instance of {@link 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 2<sup>64</sup>(2<sup>256</sup>-1) such subsequences, and each subsequence,
@@ -96,43 +97,42 @@
* 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<sup>-64</sup>.
* (Note that the set of 2<sup>64</sup> less-common subsequence values will differ from
- * one instance of {@code L64X256Random} to another, as a function of the additive
+ * one instance of {@link 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.
- *
- * <p>Method {@link #split} constructs and returns a new {@code L64X256Random}
+ * <p>
+ * Method {@link #split} constructs and returns a new {@link 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
+ * generated by a single thread using a single {@link L64X256Random} object.
+ * This is because, with high probability, distinct {@link 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.
- *
- * <p>As with {@link java.util.SplittableRandom}, instances of
- * {@code L64X256Random} are <em>not</em> thread-safe.
+ * <p>
+ * As with {@link java.util.SplittableRandom}, instances of
+ * {@link L64X256Random} are <em>not</em> 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()}.
- *
- * <p>This class provides additional methods for generating random
+ * <p>
+ * This class provides additional methods for generating random
* streams, that employ the above techniques when used in
* {@code stream.parallel()} mode.
- *
- * <p>Instances of {@code L64X256Random} are not cryptographically
+ * <p>
+ * Instances of {@link 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
+ * @since 14
*/
-public final class L64X256Random extends AbstractSplittableRng {
+public final class L64X256Random extends AbstractSplittableRNG {
/*
* Implementation Overview.
@@ -144,7 +144,7 @@
*
* 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}
+ * that the values generated by two instances of {@link L64X256Random}
* will be (approximately) independent if have different values for `a`.
*
* The default (no-argument) constructor, in essence, uses
@@ -167,13 +167,13 @@
/**
* The seed generator for default constructors.
*/
- private static final AtomicLong defaultGen = new AtomicLong(RngSupport.initialSeed());
+ 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);
+ private static final BigInteger PERIOD =
+ BigInteger.ONE.shiftLeft(256).subtract(BigInteger.ONE).shiftLeft(64);
/*
* Multiplier used in the LCG portion of the algorithm, taken from
@@ -183,7 +183,7 @@
* Table 4 (first multiplier for size 2<sup>64</sup>).
*/
- private static final long m = 2862933555777941757L;
+ private static final long M = 2862933555777941757L;
/* ---------------- instance fields ---------------- */
@@ -214,72 +214,72 @@
* @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.
+ // 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, 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);
- }
+ // 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
+ * Creates a new instance of {@link L64X256Random} using the
* specified {@code long} value as the initial seed. Instances of
- * {@code L64X256Random} created with the same seed in the same
+ * {@link 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));
+ // 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
+ * Creates a new instance of {@link 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));
+ // 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
+ * Creates a new instance of {@link L64X256Random} using the specified array of
+ * initial seed bytes. Instances of {@link 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.
+ // 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;
@@ -291,26 +291,27 @@
/* ---------------- public methods ---------------- */
/**
- * Constructs and returns a new instance of {@code L64X256Random}
+ * Constructs and returns a new instance of {@link 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
+ * a single {@link 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
+ * @param source a {@link 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}
+ *
+ * @return a new instance of {@link 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());
+ 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());
}
/**
@@ -318,15 +319,16 @@
*
* @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;
+ 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; }
+ public BigInteger period() {
+ return PERIOD;
+ }
}
--- a/src/java.base/share/classes/java/util/random/LeapableRNG.java Thu Jun 27 18:02:51 2019 -0300
+++ b/src/java.base/share/classes/java/util/random/LeapableRNG.java Thu Jun 27 18:30:27 2019 -0300
@@ -22,130 +22,114 @@
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
-package java.util;
-import java.math.BigInteger;
+package java.util.random;
+
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 <i>leap</i> 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 2<sup>128</sup> or so).
- *
- * <p>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 2<sup>64</sup>. Implementors are advised to use algorithms
- * whose period is at least 2<sup>191</sup>.
+ * 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
+ * <i>leap</i> to a very distant point in the state cycle.
+ * <p>
+ * Typically one will construct a series of {@link LeapableRNG} objects by iterative leaping from a
+ * single original {@link 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
+ * 2<sup>128</sup> or so).
+ * <p>
+ * Ideally, all {@link LeapableRNG} objects produced by iterative leaping and jumping from a single
+ * original {@link 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
+ * 2<sup>64</sup>. Implementors are advised to use algorithms whose period is at least
+ * 2<sup>191</sup>.
+ * <p>
+ * 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 {@link JumpableRNG} interface but need not also implement
+ * the {@link LeapableRNG} interface. A typical strategy for a multithreaded application is to
+ * create a single {@link 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.
+ * <p>
+ * An implementation of the {@link 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.
+ * <p>
+ * Objects that implement {@link 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.
*
- * <p>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.
- *
- * <p>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.
- *
- * <p>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
+ * @since 14
*/
-public interface LeapableRng extends JumpableRng {
+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).
+ * 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();
+ LeapableRNG copy();
/**
- * Alter the state of this pseudorandom number generator so as to
- * leap forward a large, fixed distance (typically 2<sup>96</sup>
- * or more) within its state cycle.
+ * Alter the state of this pseudorandom number generator so as to leap forward a large, fixed
+ * distance (typically 2<sup>96</sup> 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.
+ * 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.
+ * Returns an effectively unlimited stream of new pseudorandom number generators, each of which
+ * implements the {@link JumpableRNG} interface.
*
- * @implNote It is permitted to implement this method in a manner
- * equivalent to {@code leaps(Long.MAX_VALUE)}.
+ * @return a stream of objects that implement the {@link JumpableRNG} interface
*
- * @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
+ * @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.
*/
- default Stream<JumpableRng> leaps() {
- return Stream.generate(this::copyAndLeap).sequential();
+ default Stream<JumpableRNG> leaps() {
+ return Stream.generate(this::copyAndLeap).sequential();
}
/**
- * Returns a stream producing the given {@code streamSize} number of
- * new pseudorandom number generators, each of which implements the
- * {@code JumpableRng} interface.
- *
- * @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.
+ * Returns a stream producing the given {@code streamSize} number of new pseudorandom number
+ * generators, each of which implements the {@link JumpableRNG} interface.
*
* @param streamSize the number of generators to generate
- * @return a stream of objects that implement the {@code JumpableRng} interface
- * @throws IllegalArgumentException if {@code streamSize} is
- * less than zero
+ *
+ * @return a stream of objects that implement the {@link JumpableRNG} interface
+ *
+ * @throws IllegalArgumentException if {@code streamSize} is less than zero
+ * @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.
*/
- default Stream<JumpableRng> leaps(long streamSize) {
+ default Stream<JumpableRNG> leaps(long streamSize) {
return leaps().limit(streamSize);
}
-
+
/**
* Copy this generator, leap this generator forward, then return the copy.
*
* @return a copy of this generator object before the leap occurred
*/
- default JumpableRng copyAndLeap() {
- JumpableRng result = copy();
- leap();
- return result;
+ default JumpableRNG copyAndLeap() {
+ JumpableRNG result = copy();
+ leap();
+ return result;
}
}
--- a/src/java.base/share/classes/java/util/random/MRG32k3a.java Thu Jun 27 18:02:51 2019 -0300
+++ b/src/java.base/share/classes/java/util/random/MRG32k3a.java Thu Jun 27 18:30:27 2019 -0300
@@ -22,7 +22,8 @@
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
-package java.util;
+
+package java.util.random;
import java.math.BigInteger;
import java.util.concurrent.atomic.AtomicLong;
@@ -30,30 +31,29 @@
/**
* A generator of uniform pseudorandom values applicable for use in
* (among other contexts) isolated parallel computations that may
- * generate subtasks. Class {@code MRG32k3a} implements
- * interfaces {@link java.util.Rng} and {@link java.util.AbstractArbitrarilyJumpableRng},
+ * generate subtasks. Class {@link MRG32k3a} implements
+ * interfaces {@link RandomNumberGenerator} and {@link AbstractArbitrarilyJumpableRNG},
* 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 {@code Xoroshiro128PlusMRG32k3a} objects
+ * as well as creating new {@link Xoroshiro128PlusMRG32k3a} objects
* by "jumping" or "leaping".
- *
- * <p>Instances {@code Xoroshiro128Plus} are <em>not</em> thread-safe.
+ * <p>
+ * Instances {@link Xoroshiro128Plus} are <em>not</em> 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
+ * can be used to construct new instances of {@link Xoroshiro128Plus} that traverse
* other parts of the state cycle.
- *
- * <p>Instances of {@code MRG32k3a} are not cryptographically
+ * <p>
+ * Instances of {@link 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
+ * @since 14
*/
-public final class MRG32k3a extends AbstractArbitrarilyJumpableRng {
+public final class MRG32k3a extends AbstractArbitrarilyJumpableRNG {
/*
* Implementation Overview.
@@ -65,31 +65,29 @@
* 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";
+ 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;
/**
* 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.
+ 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;
+ s20, s21, s22;
/**
* The seed generator for default constructors.
*/
- private static final AtomicLong defaultGen = new AtomicLong(RngSupport.initialSeed());
+ private static final AtomicLong DEFAULT_GEN =
+ new AtomicLong(RNGSupport.initialSeed());
/*
32-bits Random number generator U(0,1): MRG32k3a
@@ -98,58 +96,59 @@
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;
+ /* 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;
+ 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 + m + ((M1_DEFICIT + 1) >>> 1) - (r = u % n) < 0;
u = (int)nextDouble() >>> 1)
;
return (r + origin);
} else {
- return RngSupport.boundedNextInt(this, origin, bound);
+ return RNGSupport.boundedNextInt(this, origin, bound);
}
} else {
- return nextInt();
- }
+ 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;
+ 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;
}
/**
@@ -157,15 +156,15 @@
* 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;
- }
+ 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 ---------------- */
@@ -186,13 +185,13 @@
* @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);
+ 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);
}
/**
@@ -206,11 +205,11 @@
*/
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));
+ (double)(((seed >>> 11) & 0x7FF) + 12345),
+ (double)(((seed >>> 22) & 0x7FF) + 12345),
+ (double)(((seed >>> 33) & 0x7FF) + 12345),
+ (double)(((seed >>> 44) & 0x7FF) + 12345),
+ (double)((seed >>> 55) + 12345));
}
/**
@@ -220,36 +219,38 @@
* may, and typically does, vary across program invocations.
*/
public MRG32k3a() {
- this(defaultGen.getAndAdd(RngSupport.GOLDEN_RATIO_64));
+ this(DEFAULT_GEN.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
+ * Creates a new instance of {@link Xoshiro256StarStar} using the specified array of
+ * initial seed bytes. Instances of {@link 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;
- }
+ // 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); }
+ public MRG32k3a copy() {
+ return new MRG32k3a(s10, s11, s12, s20, s21, s22);
+ }
/**
* Returns a pseudorandom {@code double} value between zero
@@ -259,12 +260,12 @@
* (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);
+ nextState();
+ double p1 = s12, p2 = s22;
+ if (p1 <= p2)
+ return ((p1 - p2 + M1) * NORM1);
+ else
+ return ((p1 - p2) * NORM1);
}
/**
@@ -275,14 +276,14 @@
* (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;
+ 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).
@@ -300,7 +301,7 @@
* @return a pseudorandom {@code int} value
*/
public int nextInt() {
- return (internalNextInt(0x10000) << 16) | internalNextInt(0x10000);
+ return (internalNextInt(0x10000) << 16) | internalNextInt(0x10000);
}
/**
@@ -310,147 +311,156 @@
*/
public long nextLong() {
- return (((long)internalNextInt(0x200000) << 43) |
- ((long)internalNextInt(0x200000) << 22) |
- ((long)internalNextInt(0x400000)));
+ 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);
+ 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; }
+
+ static final BigInteger PERIOD = calculateThePeriod();
+
+ public BigInteger period() {
+ return PERIOD;
+ }
// 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 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);
+ // 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<sup>{@code logDistance}</sup>
@@ -459,14 +469,15 @@
* @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<sup>{@code logDistance}</sup> 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));
+ throw new IllegalArgumentException("logDistance must be non-negative and not greater than 192");
+ jump(Math.scalb(1.0, logDistance));
}
}
--- a/src/java.base/share/classes/java/util/random/RNGSupport.java Thu Jun 27 18:02:51 2019 -0300
+++ b/src/java.base/share/classes/java/util/random/RNGSupport.java Thu Jun 27 18:30:27 2019 -0300
@@ -22,48 +22,41 @@
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
-package java.util;
-import java.util.Rng;
+package java.util.random;
+
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.DoubleStream;
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}.
+ * This class is mostly for library writers creating specific implementations of the
+ * interface {@link RandomNumberGenerator}.
*
- * @author Guy Steele
- * @author Doug Lea
- * @since 1.9
+ * @since 14
*/
-public class RngSupport {
+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}.
+ * that satisfy the interface {@link RandomNumberGenerator}.
*
* 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";
+ static final String BAD_SIZE = "size must be non-negative";
+ static final String BAD_DISTANCE = "jump distance must be finite, positive, and an exact integer";
+ static final String BAD_BOUND = "bound must be positive";
+ static final String BAD_FLOATING_BOUND = "bound must be finite and positive";
+ static final String BAD_RANGE = "bound must be greater than origin";
/* ---------------- public methods ---------------- */
@@ -71,121 +64,136 @@
* 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);
+ if (streamSize < 0L)
+ throw new IllegalArgumentException(BAD_SIZE);
}
/**
* 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
+ *
+ * @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);
+ if (!(distance > 0.0 && distance < Float.POSITIVE_INFINITY
+ && distance == Math.floor(distance))) {
+ throw new IllegalArgumentException(BAD_DISTANCE);
+ }
}
/**
* 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
+ *
+ * @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);
+ if (!(bound > 0.0 && bound < Float.POSITIVE_INFINITY)) {
+ throw new IllegalArgumentException(BAD_FLOATING_BOUND);
+ }
}
/**
* 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
+ *
+ * @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);
+ if (!(bound > 0.0 && bound < Double.POSITIVE_INFINITY)) {
+ throw new IllegalArgumentException(BAD_FLOATING_BOUND);
+ }
}
/**
* 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);
+ if (bound <= 0) {
+ throw new IllegalArgumentException(BAD_BOUND);
+ }
}
/**
* 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);
+ if (bound <= 0) {
+ throw new IllegalArgumentException(BAD_BOUND);
+ }
}
/**
* 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
+ * @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);
+ if (!(origin < bound && (bound - origin) < Float.POSITIVE_INFINITY)) {
+ throw new IllegalArgumentException(BAD_RANGE);
+ }
}
/**
* 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
+ * @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);
+ if (!(origin < bound && (bound - origin) < Double.POSITIVE_INFINITY)) {
+ throw new IllegalArgumentException(BAD_RANGE);
+ }
}
/**
* 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}
+ * @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);
+ if (origin >= bound) {
+ throw new IllegalArgumentException(BAD_RANGE);
+ }
}
/**
* 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}
+ * @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);
+ if (origin >= bound) {
+ throw new IllegalArgumentException(BAD_RANGE);
+ }
}
/**
@@ -198,35 +206,36 @@
* @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;
+ 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;
}
/**
@@ -239,35 +248,36 @@
* @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;
+ 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;
}
/*
@@ -278,8 +288,8 @@
*/
/**
- * This is the form of {@code nextLong} used by a {@code LongStream}
- * {@code Spliterator} and by the public method
+ * This is the form of {@code nextLong} used by a {@link LongStream}
+ * {@link 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
@@ -297,8 +307,8 @@
* 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).
- *
- * <p> The implementation considers four cases:
+ * <p>
+ * The implementation considers four cases:
* <ol>
*
* <li> If the {@code} bound} is less than or equal to the {@code origin}
@@ -334,35 +344,36 @@
* 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) {
+ public static long boundedNextLong(RandomNumberGenerator rng, long origin, long bound) {
long r = rng.nextLong();
if (origin < bound) {
- // It's not case (1).
+ // It's not case (1).
final long n = bound - origin;
- final long m = n - 1;
+ final long m = n - 1;
if ((n & m) == 0L) {
- // It is case (2): length of range is a power of 2.
+ // 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. */
+ } 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.
+ else {
+ // It is case (4): length of range not representable as long.
while (r < origin || r >= bound)
r = rng.nextLong();
}
@@ -388,8 +399,8 @@
* 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).
- *
- * <p> The implementation considers two cases:
+ * <p>
+ * The implementation considers two cases:
* <ol>
*
* <li> If {@code bound} is an exact power of two 2<sup><i>m</i></sup>
@@ -411,22 +422,23 @@
* @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) {
+ public static long boundedNextLong(RandomNumberGenerator 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.
+ // 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. */
+ } 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)
@@ -436,8 +448,8 @@
}
/**
- * This is the form of {@code nextInt} used by an {@code IntStream}
- * {@code Spliterator} and by the public method
+ * This is the form of {@code nextInt} used by an {@link IntStream}
+ * {@link 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
@@ -446,34 +458,35 @@
* 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}
+ *
+ * @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.
*/
- public static int boundedNextInt(Rng rng, int origin, int bound) {
+ public static int boundedNextInt(RandomNumberGenerator rng, int origin, int bound) {
int r = rng.nextInt();
if (origin < bound) {
- // It's not case (1).
+ // It's not case (1).
final int n = bound - origin;
- final int m = n - 1;
+ final int m = n - 1;
if ((n & m) == 0) {
- // It is case (2): length of range is a power of 2.
+ // 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.
+ } 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)
@@ -481,11 +494,10 @@
r += origin;
}
else {
- // It is case (4): length of range not representable as long.
- while (r < origin || r >= bound)
-
-
- r = rng.nextInt();
+ // It is case (4): length of range not representable as long.
+ while (r < origin || r >= bound) {
+ r = rng.nextInt();
+ }
}
}
return r;
@@ -500,26 +512,27 @@
* 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
+ *
+ * @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.
*/
- public static int boundedNextInt(Rng rng, int bound) {
+ public static int boundedNextInt(RandomNumberGenerator 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.
+ // The bound is a power of 2.
r &= m;
- } else {
- // Must reject over-represented candidates
+ } else {
+ // Must reject over-represented candidates
for (int u = r >>> 1;
u + m - (r = u % bound) < 0;
u = rng.nextInt() >>> 1)
@@ -527,10 +540,10 @@
}
return r;
}
-
+
/**
- * This is the form of {@code nextDouble} used by a {@code DoubleStream}
- * {@code Spliterator} and by the public method
+ * This is the form of {@code nextDouble} used by a {@link DoubleStream}
+ * {@link 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
@@ -566,7 +579,7 @@
* in which case it will be between 0.0 (inclusive)
* and 1.0 (exclusive)
*/
- public static double boundedNextDouble(Rng rng, double origin, double bound) {
+ public static double boundedNextDouble(RandomNumberGenerator rng, double origin, double bound) {
double r = rng.nextDouble();
if (origin < bound) {
r = r * (bound - origin) + origin;
@@ -575,7 +588,7 @@
}
return r;
}
-
+
/**
* This is the form of {@code nextDouble} used by the public method
* {@code nextDouble(bound)}. This is essentially a version of
@@ -596,18 +609,18 @@
* @return a pseudorandomly chosen {@code double} value
* between zero (inclusive) and {@code bound} (exclusive)
*/
- public static double boundedNextDouble(Rng rng, double bound) {
+ public static double boundedNextDouble(RandomNumberGenerator 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);
+ 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
+ * This is the form of {@code nextFloat} used by a {@code Stream<Float>}
+ * {@link 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
@@ -633,7 +646,7 @@
* in which case it will be between 0.0 (inclusive)
* and 1.0 (exclusive)
*/
- public static float boundedNextFloat(Rng rng, float origin, float bound) {
+ public static float boundedNextFloat(RandomNumberGenerator rng, float origin, float bound) {
float r = rng.nextFloat();
if (origin < bound) {
r = r * (bound - origin) + origin;
@@ -663,29 +676,29 @@
* @return a pseudorandomly chosen {@code float} value
* between zero (inclusive) and {@code bound} (exclusive)
*/
- public static float boundedNextFloat(Rng rng, float bound) {
+ public static float boundedNextFloat(RandomNumberGenerator 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);
+ 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(
+ String pp = java.security.AccessController.doPrivileged(
new sun.security.action.GetPropertyAction(
"java.util.secureRandomSeed"));
- return (pp != null && pp.equalsIgnoreCase("true"));
+ 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}
+ * initializing a source of seed values for instances of {@link RandomNumberGenerator}
* created by zero-argument constructors. (This method should
* <i>not</i> be called repeatedly, once per constructed
* object; at most it should be called once per class.)
@@ -704,31 +717,31 @@
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.
@@ -745,7 +758,7 @@
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.
@@ -762,7 +775,7 @@
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.
@@ -816,8 +829,8 @@
return z ^ (z >>> 16);
}
- // Non-public (package only) support for spliterators needed by AbstractSplittableRng
- // and AbstractArbitrarilyJumpableRng and AbstractSharedRng
+ // 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.
@@ -826,10 +839,10 @@
long index;
final long fence;
- RandomSpliterator(long index, long fence) {
- this.index = index; this.fence = fence;
+ RandomSpliterator(long index, long fence) {
+ this.index = index; this.fence = fence;
}
-
+
public long estimateSize() {
return fence - index;
}
@@ -839,10 +852,10 @@
Spliterator.NONNULL | Spliterator.IMMUTABLE);
}
}
-
-
- /*
- * Implementation support for nextExponential() and nextGaussian() methods of Rng.
+
+
+ /*
+ * Implementation support for nextExponential() and nextGaussian() methods of RandomNumberGenerator.
*
* Each is implemented using McFarland's fast modified ziggurat algorithm (largely
* table-driven, with rare cases handled by computation and rejection sampling).
@@ -872,201 +885,201 @@
// 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.
+ static double computeNextExponential(RandomNumberGenerator 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;
- }
- }
+ 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;
+ static double computeNextGaussian(RandomNumberGenerator 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;
+ 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;
- }
+ // 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.
+ 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.
+ // 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.
+ // 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.
+ 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;
+ } 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;
}
-
+
}
-
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.base/share/classes/java/util/random/RandomNumberGenerator.java Thu Jun 27 18:30:27 2019 -0300
@@ -0,0 +1,639 @@
+/*
+ * Copyright (c) 2016, 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.random;
+
+import java.math.BigInteger;
+import java.util.stream.DoubleStream;
+import java.util.stream.IntStream;
+import java.util.stream.LongStream;
+
+/**
+ * The {@link RandomNumberGenerator} 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.
+ * <p>
+ * 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.
+ * <p>
+ * In the case of {@code int}, {@code long}, and {@link Boolean} values, if there is no explicit
+ * specification of range, then the range includes all possible values of the type. In the case of
+ * {@code float} and {@code double} values, a value is always chosen from the set of
+ * 2<sup><i>w</i></sup> values between 0.0 (inclusive) and 1.0 (exclusive), where <i>w</i> is 23 for
+ * {@code float} values and 52 for {@code double} values, such that adjacent values differ by
+ * 2<sup>−<i>w</i></sup>; 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.
+ * <p>
+ * 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 {@link RandomNumberGenerator}, 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.
+ * <p>
+ * Every object that implements the {@link RandomNumberGenerator} 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
+ * <i>period</i>. (Some implementations of the {@link RandomNumberGenerator} 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.)
+ * <p>
+ * As a rule, objects that implement the {@link RandomNumberGenerator} interface need not be
+ * thread-safe. It is recommended that multithreaded applications use either {@link
+ * ThreadLocalRandom} or (preferably) pseudorandom number generators that implement the {@link
+ * SplittableRNG} or {@link JumpableRNG} interface.
+ * <p>
+ * 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 JumpableRNG} or {@link LeapableRNG}, or to extend an abstract
+ * class such as {@link AbstractSplittableRNG} or {@link AbstractArbitrarilyJumpableRNG}.
+ * <p>
+ * Objects that implement {@link RandomNumberGenerator} 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 {@link RandomNumberGenerator} 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.
+ *
+ * @since 14
+ */
+public interface RandomNumberGenerator {
+
+ /**
+ * Returns an effectively unlimited stream of pseudorandomly chosen
+ * {@code double} values.
+ *
+ * @return a 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()}.
+ */
+ 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).
+ *
+ * @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}
+ *
+ * @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)}.
+ */
+ 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.
+ *
+ * @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
+ *
+ * @implNote The default implementation produces a sequential stream
+ * that repeatedly calls {@code nextDouble()}.
+ */
+ 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).
+ *
+ * @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}
+ *
+ * @implNote The default implementation produces a sequential stream
+ * that repeatedly calls {@code nextDouble(randomNumberOrigin, 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.
+ *
+ * @return a 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()}.
+ */
+ 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).
+ *
+ * @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}
+ *
+ * @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)}.
+ */
+ 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.
+ *
+ * @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
+ *
+ * @implNote The default implementation produces a sequential stream
+ * that repeatedly calls {@code nextInt()}.
+ */
+ 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).
+ *
+ * @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}
+ *
+ * @implNote The default implementation produces a sequential stream that repeatedly
+ * calls {@code nextInt(randomNumberOrigin, 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.
+ *
+ * @return a 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()}.
+ */
+ 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).
+ *
+ * @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}
+ *
+ * @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)}.
+ */
+ 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.
+ *
+ * @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
+ *
+ * @implNote The default implementation produces a sequential stream
+ * that repeatedly calls {@code nextLong()}.
+ */
+ 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).
+ *
+ * @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}
+ *
+ * @implNote The default implementation produces a sequential stream that repeatedly
+ * calls {@code nextLong(randomNumberOrigin, 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.
+ * <p>
+ * 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).
+ * <p>
+ * 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).
+ *
+ * @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
+ *
+ * @implNote The default implementation simply calls
+ * {@code RNGSupport.checkBound(bound)} and then
+ * {@code RNGSupport.boundedNextFloat(this, bound)}.
+ */
+ 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).
+ *
+ * @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}
+ *
+ * @implNote The default implementation simply calls
+ * {@code RNGSupport.checkRange(origin, bound)} and then
+ * {@code RNGSupport.boundedNextFloat(this, origin, 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).
+ * <p>
+ * 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).
+ *
+ * @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
+ *
+ * @implNote The default implementation simply calls
+ * {@code RNGSupport.checkBound(bound)} and then
+ * {@code RNGSupport.boundedNextDouble(this, bound)}.
+ */
+ 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).
+ *
+ * @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}
+ *
+ * @implNote The default implementation simply calls
+ * {@code RNGSupport.checkRange(origin, bound)} and then
+ * {@code RNGSupport.boundedNextDouble(this, origin, 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.
+ * <p>
+ * 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).
+ *
+ * @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
+ *
+ * @implNote The default implementation simply calls
+ * {@code RNGSupport.checkBound(bound)} and then
+ * {@code RNGSupport.boundedNextInt(this, bound)}.
+ */
+ 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).
+ *
+ * @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}
+ *
+ * @implNote The default implementation simply calls
+ * {@code RNGSupport.checkRange(origin, bound)} and then
+ * {@code RNGSupport.boundedNextInt(this, origin, 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).
+ *
+ * @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
+ *
+ * @implNote The default implementation simply calls
+ * {@code RNGSupport.checkBound(bound)} and then
+ * {@code RNGSupport.boundedNextLong(this, bound)}.
+ */
+ 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).
+ *
+ * @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}
+ *
+ * @implNote The default implementation simply calls
+ * {@code RNGSupport.checkRange(origin, bound)} and then
+ * {@code RNGSupport.boundedNextInt(this, origin, 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 {@link RandomNumberGenerator} object.
+ *
+ * @return a {@link BigInteger} whose value is the number of distinct possible states of this
+ * {@link RandomNumberGenerator} 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);
+}
--- a/src/java.base/share/classes/java/util/random/SplittableRNG.java Thu Jun 27 18:02:51 2019 -0300
+++ b/src/java.base/share/classes/java/util/random/SplittableRNG.java Thu Jun 27 18:30:27 2019 -0300
@@ -22,7 +22,8 @@
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
-package java.util;
+
+package java.util.random;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
@@ -36,69 +37,68 @@
* and furthermore can be <i>split</i> into two objects (the original
* one and a new one) each of which obey that same protocol (and therefore
* can be recursively split indefinitely).
- *
- * <p>Ideally, all {@code SplittableRNG} objects produced by recursive
- * splitting from a single original {@code SplittableRNG} object are
+ * <p>
+ * Ideally, all {@link SplittableRNG} objects produced by recursive
+ * splitting from a single original {@link 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
+ * using a single {@link SplittableRNG} object. In practice, one must
* settle for some approximation to independence and uniformity.
- *
- * <p>Methods are provided to perform a single splitting operation and
+ * <p>
+ * 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).
- *
- * <p>An implementation of the {@code SplittableRng} interface must provide
+ * <p>
+ * An implementation of the {@link 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
+ * {@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}.
- *
- * <p>Objects that implement {@code java.util.SplittableRNG} are
+ * {@link AbstractSplittableRNG}.
+ * <p>
+ * Objects that implement {@link 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
+ * @since 14
*/
-public interface SplittableRng extends StreamableRng {
+public interface SplittableRNG extends StreamableRNG {
/**
* Returns a new pseudorandom number generator, split off from
- * this one, that implements the {@code Rng} and {@code SplittableRng}
+ * this one, that implements the {@link RandomNumberGenerator} and {@link 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
+ * @return a new object that implements the {@link RandomNumberGenerator} and
+ * {@link SplittableRNG} interfaces
*/
- SplittableRng split();
+ SplittableRNG split();
/**
* Returns a new pseudorandom number generator, split off from
- * this one, that implements the {@code Rng} and {@code SplittableRng}
+ * this one, that implements the {@link RandomNumberGenerator} and {@link SplittableRNG}
* interfaces.
*
- * @param source a {@code SplittableRng} instance to be used instead
+ * @param source a {@link 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
+ * @return an object that implements the {@link RandomNumberGenerator} and
+ * {@link SplittableRNG} interfaces
*/
- SplittableRng split(SplittableRng source);
+ SplittableRNG split(SplittableRNG source);
/**
* Returns an effectively unlimited stream of new pseudorandom
- * number generators, each of which implements the {@code SplittableRng}
+ * number generators, each of which implements the {@link SplittableRNG}
* interface.
*
* This pseudorandom number generator may be used as a source of
@@ -107,86 +107,92 @@
* @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
+ * @return a stream of {@link SplittableRNG} objects
*/
- default Stream<SplittableRng> splits() {
- return this.splits(this);
+ default Stream<SplittableRNG> splits() {
+ return this.splits(this);
}
/**
* Returns a stream producing the given {@code streamSize} number of
* new pseudorandom number generators, each of which implements the
- * {@code SplittableRng} interface.
+ * {@link SplittableRNG} interface.
*
* This pseudorandom number generator may be used as a source of
* pseudorandom bits used to initialize the state the new ones.
*
* @param streamSize the number of values to generate
- * @return a stream of {@code SplittableRng} objects
+ *
+ * @return a stream of {@link SplittableRNG} objects
+ *
* @throws IllegalArgumentException if {@code streamSize} is
* less than zero
*/
- Stream<SplittableRng> splits(long streamSize);
+ Stream<SplittableRNG> splits(long streamSize);
/**
* Returns an effectively unlimited stream of new pseudorandom
- * number generators, each of which implements the {@code SplittableRng}
+ * number generators, each of which implements the {@link SplittableRNG}
* interface.
*
- * @implNote It is permitted to implement this method in a manner
- * equivalent to {@code splits(Long.MAX_VALUE, source)}.
- *
- * @param source a {@code SplittableRng} instance to be used instead
+ * @param source a {@link 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 stream of {@code SplittableRng} objects
+ * @return a stream of {@link SplittableRNG} objects
+ *
+ * @implNote It is permitted to implement this method in a manner
+ * equivalent to {@code splits(Long.MAX_VALUE, source)}.
*/
- Stream<SplittableRng> splits(SplittableRng source);
+ Stream<SplittableRNG> splits(SplittableRNG source);
/**
* Returns a stream producing the given {@code streamSize} number of
* new pseudorandom number generators, each of which implements the
- * {@code SplittableRng} interface.
+ * {@link SplittableRNG} interface.
*
* @param streamSize the number of values to generate
- * @param source a {@code SplittableRng} instance to be used instead
+ * @param source a {@link 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 stream of {@code SplittableRng} objects
+ *
+ * @return a stream of {@link SplittableRNG} objects
+ *
* @throws IllegalArgumentException if {@code streamSize} is
* less than zero
*/
- Stream<SplittableRng> splits(long streamSize, SplittableRng source);
+ Stream<SplittableRNG> splits(long streamSize, SplittableRNG source);
/**
* Returns an effectively unlimited stream of new pseudorandom
- * number generators, each of which implements the {@code Rng}
+ * number generators, each of which implements the {@link RandomNumberGenerator}
* interface. Ideally the generators in the stream will appear
* to be statistically independent.
*
- * @implNote The default implementation calls {@code splits()}.
+ * @return a stream of objects that implement the {@link RandomNumberGenerator} interface
*
- * @return a stream of objects that implement the {@code Rng} interface
+ * @implNote The default implementation calls {@code splits()}.
*/
- default Stream<Rng> rngs() {
- return this.splits().map(x -> (Rng)x);
+ default Stream<RandomNumberGenerator> rngs() {
+ return this.splits().map(x -> (RandomNumberGenerator)x);
}
/**
* Returns a stream producing the given {@code streamSize} number of
* new pseudorandom number generators, each of which implements the
- * {@code Rng} interface. Ideally the generators in the stream will
+ * {@link RandomNumberGenerator} interface. Ideally the generators in the stream will
* appear to be statistically independent.
*
- * @implNote The default implementation calls {@code splits(streamSize)}.
- *
* @param streamSize the number of generators to generate
- * @return a stream of objects that implement the {@code Rng} interface
+ *
+ * @return a stream of objects that implement the {@link RandomNumberGenerator} interface
+ *
* @throws IllegalArgumentException if {@code streamSize} is
* less than zero
+ *
+ * @implNote The default implementation calls {@code splits(streamSize)}.
*/
- default Stream<Rng> rngs(long streamSize) {
- return this.splits(streamSize).map(x -> (Rng)x);
+ default Stream<RandomNumberGenerator> rngs(long streamSize) {
+ return this.splits(streamSize).map(x -> (RandomNumberGenerator)x);
}
}
--- a/src/java.base/share/classes/java/util/random/StreamableRNG.java Thu Jun 27 18:02:51 2019 -0300
+++ b/src/java.base/share/classes/java/util/random/StreamableRNG.java Thu Jun 27 18:30:27 2019 -0300
@@ -22,79 +22,79 @@
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
-package java.util;
-import java.util.Rng;
-import java.util.RngSupport;
+package java.util.random;
+
import java.util.stream.Stream;
/**
- * The {@code StreamableRng} interface augments the {@code Rng} interface
- * to provide methods that return streams of {@code Rng} objects.
+ * The {@link StreamableRNG} interface augments the {@link RandomNumberGenerator} interface
+ * to provide methods that return streams of {@link RandomNumberGenerator} objects.
* Ideally, such a stream of objects would have the property that the
* behavior of each object is statistically independent of all the others.
* In practice, one may have to settle for some approximation to this property.
*
- * A generator that implements interface {@link java.util.SplittableRng}
+ * A generator that implements interface {@link SplittableRNG}
* may choose to use its {@code splits} method to implement the {@code rngs}
* method required by this interface.
*
- * A generator that implements interface {@link java.util.JumpableRng}
+ * A generator that implements interface {@link JumpableRNG}
* may choose to use its {@code jumps} method to implement the {@code rngs}
* method required by this interface.
*
- * A generator that implements interface {@link java.util.LeapableRng}
+ * A generator that implements interface {@link LeapableRNG}
* may choose to use its {@code leaps} method to implement the {@code rngs}
* method required by this interface.
- *
- * <p>An implementation of the {@code StreamableRng} interface must provide
+ * <p>
+ * An implementation of the {@link 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.
- *
- * <p>Objects that implement {@code java.util.StreamableRng} are typically
+ * <p>
+ * Objects that implement {@link 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
+ * @since 14
*/
-public interface StreamableRng extends Rng {
+public interface StreamableRNG extends RandomNumberGenerator {
/**
* Returns an effectively unlimited stream of objects, each of
- * which implements the {@code Rng} interface. Ideally the
+ * which implements the {@link RandomNumberGenerator} 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 {@link RandomNumberGenerator} interface
*
- * @return a stream of objects that implement the {@code Rng} interface
+ * @implNote It is permitted to implement this method in a manner
+ * equivalent to {@code rngs(Long.MAX_VALUE)}.
*/
- Stream<Rng> rngs();
+ Stream<RandomNumberGenerator> rngs();
/**
* Returns an effectively unlimited stream of objects, each of
- * which implements the {@code Rng} interface. Ideally the
+ * which implements the {@link RandomNumberGenerator} 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 The default implementation calls {@code rngs()} and
- * then limits its length to {@code streamSize}.
+ * @param streamSize the number of generators to generate
*
- * @param streamSize the number of generators to generate
- * @return a stream of objects that implement the {@code Rng} interface
+ * @return a stream of objects that implement the {@link RandomNumberGenerator} interface
+ *
* @throws IllegalArgumentException if {@code streamSize} is
* less than zero
+ *
+ * @implNote The default implementation calls {@code rngs()} and
+ * then limits its length to {@code streamSize}.
*/
- default Stream<Rng> rngs(long streamSize) {
- RngSupport.checkStreamSize(streamSize);
+ default Stream<RandomNumberGenerator> rngs(long streamSize) {
+ RNGSupport.checkStreamSize(streamSize);
return rngs().limit(streamSize);
}
}
--- a/src/java.base/share/classes/java/util/random/Xoroshiro128Plus.java Thu Jun 27 18:02:51 2019 -0300
+++ b/src/java.base/share/classes/java/util/random/Xoroshiro128Plus.java Thu Jun 27 18:30:27 2019 -0300
@@ -22,7 +22,8 @@
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
-package java.util;
+
+package java.util.random;
import java.math.BigInteger;
import java.util.concurrent.atomic.AtomicLong;
@@ -30,14 +31,14 @@
/**
* A generator of uniform pseudorandom values applicable for use in
* (among other contexts) isolated parallel computations that may
- * generate subtasks. Class {@code Xoroshiro128Plus} implements
- * interfaces {@link java.util.Rng} and {@link java.util.LeapableRng},
+ * generate subtasks. Class {@link Xoroshiro128Plus} implements
+ * interfaces {@link RandomNumberGenerator} and {@link LeapableRNG},
* 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 {@code Xoroshiro128Plus} objects
+ * as well as creating new {@link Xoroshiro128Plus} objects
* by "jumping" or "leaping".
- *
- * <p>Series of generated values pass the TestU01 BigCrush and PractRand test suites
+ * <p>
+ * Series of generated values pass the TestU01 BigCrush and PractRand test suites
* that measure independence and uniformity properties of random number generators,
* <em>except</em> 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.
@@ -45,39 +46,37 @@
* 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.
- *
- * <p>The class {@code Xoroshiro128Plus} uses the {@code xoroshiro128} algorithm,
+ * <p>
+ * The class {@link 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 2<sup>128</sup>-1.
- *
- * <p>The 64-bit values produced by the {@code nextLong()} method are equidistributed.
+ * <p>
+ * The 64-bit values produced by the {@code nextLong()} method are equidistributed.
* To be precise, over the course of the cycle of length 2<sup>128</sup>-1,
* each nonzero {@code long} value is generated 2<sup>64</sup> times,
* but the value 0 is generated only 2<sup>64</sup>-1 times.
* The values produced by the {@code nextInt()}, {@code nextFloat()}, and {@code nextDouble()}
* methods are likewise equidistributed.
- *
- * <p>Instances {@code Xoroshiro128Plus} are <em>not</em> thread-safe.
+ * <p>
+ * Instances {@link Xoroshiro128Plus} are <em>not</em> 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
+ * can be used to construct new instances of {@link Xoroshiro128Plus} that traverse
* other parts of the state cycle.
- *
- * <p>Instances of {@code Xoroshiro128Plus} are not cryptographically
+ * <p>
+ * Instances of {@link 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
+ * @since 14
*/
-public final class Xoroshiro128Plus implements LeapableRng {
+public final class Xoroshiro128Plus implements LeapableRNG {
/*
* Implementation Overview.
@@ -110,7 +109,7 @@
*
* 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}.
+ * defined by classes {@link AbstractJumpableRNG} and {@link AbstractRNG}.
*/
/* ---------------- static fields ---------------- */
@@ -118,13 +117,13 @@
/**
* The seed generator for default constructors.
*/
- private static final AtomicLong defaultGen = new AtomicLong(RngSupport.initialSeed());
+ 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);
+ private static final BigInteger PERIOD =
+ BigInteger.ONE.shiftLeft(128).subtract(BigInteger.ONE);
/* ---------------- instance fields ---------------- */
@@ -145,92 +144,92 @@
* @param x1 second word of the initial state
*/
public Xoroshiro128Plus(long x0, long x1) {
- this.x0 = x0;
+ this.x0 = x0;
this.x1 = x1;
- // If x0 and x1 are both zero, we must choose nonzero values.
+ // 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);
- }
+ // 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
+ * Creates a new instance of {@link Xoroshiro128Plus} using the
* specified {@code long} value as the initial seed. Instances of
- * {@code Xoroshiro128Plus} created with the same seed in the same
+ * {@link 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));
+ // 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
+ * Creates a new instance of {@link 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));
+ // 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
+ * Creates a new instance of {@link Xoroshiro128Plus} using the specified array of
+ * initial seed bytes. Instances of {@link 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];
+ // 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 <http://creativecommons.org/publicdomain/zero/1.0/>. */
-
-/* This is the successor to xorshift128+. It is the fastest full-period
- generator passing BigCrush without systematic failures, but due to the
- relatively short period it is acceptable only for applications with a
- mild amount of parallelism; otherwise, use a xorshift1024* generator.
+ /*
+ * 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.
+ * <p>
+ * See <http://creativecommons.org/publicdomain/zero/1.0/>.
+ */
- Beside passing BigCrush, this generator passes the PractRand test suite
- up to (and included) 16TB, with the exception of binary rank tests,
- which fail due to the lowest bit being an LFSR; all other bits pass all
- tests. We suggest to use a sign test to extract a random Boolean value.
-
- Note that the generator uses a simulated rotate operation, which most C
- compilers will turn into a single instruction. In Java, you can use
- Long.rotateLeft(). In languages that do not make low-level rotation
- instructions accessible xorshift128+ could be faster.
-
- The state must be seeded so that it is not everywhere zero. If you have
- a 64-bit seed, we suggest to seed a splitmix64 generator and use its
- output to fill s. */
-
+ /*
+ * This is the successor to xorshift128+. It is the fastest full-period generator passing
+ * BigCrush without systematic failures, but due to the relatively short period it is acceptable
+ * only for applications with a mild amount of parallelism; otherwise, use a xorshift1024*
+ * generator.
+ * <p>
+ * Beside passing BigCrush, this generator passes the PractRand test suite up to (and included)
+ * 16TB, with the exception of binary rank tests, which fail due to the lowest bit being an
+ * LFSR; all other bits pass all tests. We suggest to use a sign test to extract a random
+ * Boolean value.
+ * <p>
+ * Note that the generator uses a simulated rotate operation, which most C compilers will turn
+ * into a single instruction. In Java, you can use Long.rotateLeft(). In languages that do not
+ * make low-level rotation instructions accessible xorshift128+ could be faster.
+ * <p>
+ * The state must be seeded so that it is not everywhere zero. If you have a 64-bit seed, we
+ * suggest to seed a splitmix64 generator and use its output to fill s.
+ */
/**
* Returns a pseudorandom {@code long} value.
@@ -238,52 +237,63 @@
* @return a pseudorandom {@code long} value
*/
public long nextLong() {
- final long s0 = x0;
- long s1 = x1;
- final long z = s0 + s1;
+ final long s0 = x0;
+ long s1 = x1;
+ final long z = s0 + s1;
- s1 ^= s0;
- x0 = Long.rotateLeft(s0, 24) ^ s1 ^ (s1 << 16); // a, b
- x1 = Long.rotateLeft(s1, 37); // c
+ s1 ^= s0;
+ x0 = Long.rotateLeft(s0, 24) ^ s1 ^ (s1 << 16); // a, b
+ x1 = Long.rotateLeft(s1, 37); // c
- return z;
+ return z;
}
- public BigInteger period() { return thePeriod; }
+ public BigInteger period() {
+ return PERIOD;
+ }
- public double defaultJumpDistance() { return 0x1.0p64; }
+ public double defaultJumpDistance() {
+ return 0x1.0p64;
+ }
- public double defaultLeapDistance() { return 0x1.0p96; }
+ public double defaultLeapDistance() {
+ return 0x1.0p96;
+ }
private static final long[] JUMP_TABLE = { 0xdf900294d8f554a5L, 0x170865df4b3201fcL };
-
+
private static final long[] LEAP_TABLE = { 0xd2a98b26625eee7bL, 0xdddf9b1090aa7ac1L };
-
-/* This is the jump function for the generator. It is equivalent
- to 2**64 calls to nextLong(); it can be used to generate 2**64
- 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**96 calls to next(); it can be used to generate 2**32 starting points,
- from each of which jump() will generate 2**32 non-overlapping
- subsequences for parallel distributed computations. */
+ /*
+ * This is the jump function for the generator. It is equivalent
+ * to 2**64 calls to nextLong(); it can be used to generate 2**64
+ * non-overlapping subsequences for parallel computations.
+ */
+ public void jump() {
+ jumpAlgorithm(JUMP_TABLE);
+ }
- public void leap() { jumpAlgorithm(LEAP_TABLE); }
+ /**
+ * This is the long-jump function for the generator. It is equivalent to 2**96 calls to next();
+ * it can be used to generate 2**32 starting points, from each of which jump() will generate
+ * 2**32 non-overlapping subsequences for parallel distributed computations.
+ */
+ public void leap() {
+ jumpAlgorithm(LEAP_TABLE);
+ }
private void jumpAlgorithm(long[] table) {
- long s0 = 0, s1 = 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;
- }
- nextLong();
- }
- x0 = s0;
- x1 = s1;
- }
+ long s0 = 0, s1 = 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;
+ }
+ nextLong();
+ }
+ x0 = s0;
+ x1 = s1;
+ }
}
}
--- a/src/java.base/share/classes/java/util/random/Xoroshiro128StarStar.java Thu Jun 27 18:02:51 2019 -0300
+++ b/src/java.base/share/classes/java/util/random/Xoroshiro128StarStar.java Thu Jun 27 18:30:27 2019 -0300
@@ -22,7 +22,8 @@
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
-package java.util;
+
+package java.util.random;
import java.math.BigInteger;
import java.util.concurrent.atomic.AtomicLong;
@@ -30,30 +31,30 @@
/**
* A generator of uniform pseudorandom values applicable for use in
* (among other contexts) isolated parallel computations that may
- * generate subtasks. Class {@code Xoroshiro128StarStar} implements
- * interfaces {@link java.util.Rng} and {@link java.util.LeapableRng},
+ * generate subtasks. Class {@link Xoroshiro128StarStar} implements
+ * interfaces {@link RandomNumberGenerator} and {@link LeapableRNG},
* 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 {@code Xoroshiro128StarStar} objects
+ * as well as creating new {@link Xoroshiro128StarStar} objects
* by "jumping" or "leaping".
- *
- * <p>Series of generated values pass the TestU01 BigCrush and PractRand test suites
+ * <p>
+ * Series of generated values pass the TestU01 BigCrush and PractRand test suites
* that measure independence and uniformity properties of random number generators.
- *
- * <p>The class {@code Xoroshiro128StarStar} uses the {@code xoroshiro128} algorithm,
+ * <p>
+ * The class {@link 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 2<sup>128</sup>-1.
- *
- * <p>The 64-bit values produced by the {@code nextLong()} method are equidistributed.
+ * <p>
+ * The 64-bit values produced by the {@code nextLong()} method are equidistributed.
* To be precise, over the course of the cycle of length 2<sup>128</sup>-1,
* each nonzero {@code long} value is generated 2<sup>64</sup> times,
* but the value 0 is generated only 2<sup>64</sup>-1 times.
* The values produced by the {@code nextInt()}, {@code nextFloat()}, and {@code nextDouble()}
* methods are likewise equidistributed.
- *
- * <p>In fact, the 64-bit values produced by the {@code nextLong()} method are 2-equidistributed.
+ * <p>
+ * 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 2<sup>128</sup>-1 such subsequences, and each subsequence,
@@ -64,25 +65,23 @@
* 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.
- *
- * <p>Instances {@code Xoroshiro128StarStar} are <em>not</em> thread-safe.
+ * <p>
+ * Instances {@link Xoroshiro128StarStar} are <em>not</em> 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
+ * can be used to construct new instances of {@link Xoroshiro128StarStar} that traverse
* other parts of the state cycle.
- *
- * <p>Instances of {@code Xoroshiro128StarStar} are not cryptographically
+ * <p>
+ * Instances of {@link 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
+ * @since 14
*/
-public final class Xoroshiro128StarStar implements LeapableRng {
+public final class Xoroshiro128StarStar implements LeapableRNG {
/*
* Implementation Overview.
@@ -115,7 +114,7 @@
*
* 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}.
+ * defined by classes {@link AbstractJumpableRNG} and {@link AbstractRNG}.
*/
/* ---------------- static fields ---------------- */
@@ -123,13 +122,13 @@
/**
* The seed generator for default constructors.
*/
- private static final AtomicLong defaultGen = new AtomicLong(RngSupport.initialSeed());
+ private static final AtomicLong DEFAULT_GEN = 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);
+ private static final BigInteger PERIOD =
+ BigInteger.ONE.shiftLeft(128).subtract(BigInteger.ONE);
/* ---------------- instance fields ---------------- */
@@ -150,92 +149,91 @@
* @param x1 second word of the initial state
*/
public Xoroshiro128StarStar(long x0, long x1) {
- this.x0 = x0;
+ this.x0 = x0;
this.x1 = x1;
- // If x0 and x1 are both zero, we must choose nonzero values.
+ // 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);
- }
+ // 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
+ * Creates a new instance of {@link Xoroshiro128StarStar} using the
* specified {@code long} value as the initial seed. Instances of
- * {@code Xoroshiro128StarStar} created with the same seed in the same
+ * {@link 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));
+ // 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
+ * Creates a new instance of {@link 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));
+ // Using GOLDEN_RATIO_64 here gives us a good Weyl sequence of values.
+ this(DEFAULT_GEN.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
+ * Creates a new instance of {@link Xoroshiro128StarStar} using the specified array of
+ * initial seed bytes. Instances of {@link 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];
+ // 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 <http://creativecommons.org/publicdomain/zero/1.0/>. */
-
-/* This is the successor to xorshift128+. It is the fastest full-period
- generator passing BigCrush without systematic failures, but due to the
- relatively short period it is acceptable only for applications with a
- mild amount of parallelism; otherwise, use a xorshift1024* generator.
+ /*
+ * 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.
+ * <p>
+ * See <http://creativecommons.org/publicdomain/zero/1.0/>.
+ */
- Beside passing BigCrush, this generator passes the PractRand test suite
- up to (and included) 16TB, with the exception of binary rank tests,
- which fail due to the lowest bit being an LFSR; all other bits pass all
- tests. We suggest to use a sign test to extract a random Boolean value.
-
- Note that the generator uses a simulated rotate operation, which most C
- compilers will turn into a single instruction. In Java, you can use
- Long.rotateLeft(). In languages that do not make low-level rotation
- instructions accessible xorshift128+ could be faster.
-
- The state must be seeded so that it is not everywhere zero. If you have
- a 64-bit seed, we suggest to seed a splitmix64 generator and use its
- output to fill s. */
-
+ /*
+ * This is the successor to xorshift128+. It is the fastest full-period generator passing
+ * BigCrush without systematic failures, but due to the relatively short period it is acceptable
+ * only for applications with a mild amount of parallelism; otherwise, use a xorshift1024*
+ * generator.
+ * <p>
+ * Beside passing BigCrush, this generator passes the PractRand test suite up to (and included)
+ * 16TB, with the exception of binary rank tests, which fail due to the lowest bit being an
+ * LFSR; all other bits pass all tests. We suggest to use a sign test to extract a random
+ * Boolean value.
+ * <p>
+ * Note that the generator uses a simulated rotate operation, which most C compilers will turn
+ * into a single instruction. In Java, you can use Long.rotateLeft(). In languages that do not
+ * make low-level rotation instructions accessible xorshift128+ could be faster.
+ * <p>
+ * The state must be seeded so that it is not everywhere zero. If you have a 64-bit seed, we
+ * suggest to seed a splitmix64 generator and use its output to fill s.
+ */
/**
* Returns a pseudorandom {@code long} value.
@@ -243,52 +241,62 @@
* @return a pseudorandom {@code long} value
*/
public long nextLong() {
- final long s0 = x0;
- long s1 = x1;
- final long z = s0;
+ final long s0 = x0;
+ long s1 = x1;
+ final long z = s0;
- s1 ^= s0;
- x0 = Long.rotateLeft(s0, 24) ^ s1 ^ (s1 << 16); // a, b
- x1 = Long.rotateLeft(s1, 37); // c
-
- return Long.rotateLeft(z * 5, 7) * 9; // "starstar" mixing function
+ s1 ^= s0;
+ x0 = Long.rotateLeft(s0, 24) ^ s1 ^ (s1 << 16); // a, b
+ x1 = Long.rotateLeft(s1, 37); // c
+
+ return Long.rotateLeft(z * 5, 7) * 9; // "starstar" mixing function
}
- public BigInteger period() { return thePeriod; }
+ public BigInteger period() {
+ return PERIOD;
+ }
- public double defaultJumpDistance() { return 0x1.0p64; }
+ public double defaultJumpDistance() {
+ return 0x1.0p64;
+ }
- public double defaultLeapDistance() { return 0x1.0p96; }
+ public double defaultLeapDistance() {
+ return 0x1.0p96;
+ }
private static final long[] JUMP_TABLE = { 0xdf900294d8f554a5L, 0x170865df4b3201fcL };
-
+
private static final long[] LEAP_TABLE = { 0xd2a98b26625eee7bL, 0xdddf9b1090aa7ac1L };
-
-/* This is the jump function for the generator. It is equivalent
- to 2**64 calls to nextLong(); it can be used to generate 2**64
- 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**96 calls to next(); it can be used to generate 2**32 starting points,
- from each of which jump() will generate 2**32 non-overlapping
- subsequences for parallel distributed computations. */
+ /**
+ * This is the jump function for the generator. It is equivalent to 2**64 calls to nextLong();
+ * it can be used to generate 2**64 non-overlapping subsequences for parallel computations.
+ */
+ public void jump() {
+ jumpAlgorithm(JUMP_TABLE);
+ }
- public void leap() { jumpAlgorithm(LEAP_TABLE); }
+ /**
+ * This is the long-jump function for the generator. It is equivalent to 2**96 calls to next();
+ * it can be used to generate 2**32 starting points, from each of which jump() will generate
+ * 2**32 non-overlapping subsequences for parallel distributed computations.
+ */
+ public void leap() {
+ jumpAlgorithm(LEAP_TABLE);
+ }
private void jumpAlgorithm(long[] table) {
- long s0 = 0, s1 = 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;
- }
- nextLong();
- }
- x0 = s0;
- x1 = s1;
- }
+ long s0 = 0, s1 = 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;
+ }
+ nextLong();
+ }
+ x0 = s0;
+ x1 = s1;
+ }
}
}
--- a/src/java.base/share/classes/java/util/random/Xoshiro256StarStar.java Thu Jun 27 18:02:51 2019 -0300
+++ b/src/java.base/share/classes/java/util/random/Xoshiro256StarStar.java Thu Jun 27 18:30:27 2019 -0300
@@ -22,7 +22,8 @@
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
-package java.util;
+
+package java.util.random;
import java.math.BigInteger;
import java.util.concurrent.atomic.AtomicLong;
@@ -30,14 +31,14 @@
/**
* A generator of uniform pseudorandom values applicable for use in
* (among other contexts) isolated parallel computations that may
- * generate subtasks. Class {@code Xoshiro256StarStar} implements
- * interfaces {@link java.util.Rng} and {@link java.util.LeapableRng},
+ * generate subtasks. Class {@link Xoshiro256StarStar} implements
+ * interfaces {@link RandomNumberGenerator} and {@link LeapableRNG},
* 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 {@code Xoshiro256StarStar} objects
+ * as well as creating new {@link Xoshiro256StarStar} objects
* by "jumping" or "leaping".
- *
- * <p>Series of generated values pass the TestU01 BigCrush and PractRand test suites
+ * <p>
+ * 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
* <a href="http://simul.iro.umontreal.ca/testu01/tu01.html">version 1.2.3 of TestU01</a>
@@ -47,21 +48,21 @@
* 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.
- *
- * <p>The class {@code Xoshiro256StarStar} uses the {@code xoshiro256} algorithm,
+ * <p>
+ * The class {@link 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 2<sup>256</sup>-1.
- *
- * <p>The 64-bit values produced by the {@code nextLong()} method are equidistributed.
+ * <p>
+ * The 64-bit values produced by the {@code nextLong()} method are equidistributed.
* To be precise, over the course of the cycle of length 2<sup>256</sup>-1,
* each nonzero {@code long} value is generated 2<sup>192</sup> times,
* but the value 0 is generated only 2<sup>192</sup>-1 times.
* The values produced by the {@code nextInt()}, {@code nextFloat()}, and {@code nextDouble()}
* methods are likewise equidistributed.
- *
- * <p>In fact, the 64-bit values produced by the {@code nextLong()} method are 4-equidistributed.
+ * <p>
+ * 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 2<sup>256</sup>-1 such subsequences, and each subsequence,
@@ -72,24 +73,23 @@
* 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.
- *
- * <p>Instances {@code Xoshiro256StarStar} are <em>not</em> thread-safe.
+ * <p>
+ * Instances {@link Xoshiro256StarStar} are <em>not</em> 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
+ * can be used to construct new instances of {@link Xoshiro256StarStar} that traverse
* other parts of the state cycle.
- *
- * <p>Instances of {@code Xoshiro256StarStar} are not cryptographically
+ * <p>
+ * Instances of {@link 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
+ * @since 14
*/
-public final class Xoshiro256StarStar implements LeapableRng {
+public final class Xoshiro256StarStar implements LeapableRNG {
/*
* Implementation Overview.
@@ -128,13 +128,13 @@
/**
* The seed generator for default constructors.
*/
- private static final AtomicLong defaultGen = new AtomicLong(RngSupport.initialSeed());
+ private static final AtomicLong DEFAULT_GEN = 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);
+ private static final BigInteger PERIOD =
+ BigInteger.ONE.shiftLeft(256).subtract(BigInteger.ONE);
/* ---------------- instance fields ---------------- */
@@ -157,63 +157,63 @@
* @param x3 fourth word of the initial state
*/
public Xoshiro256StarStar(long x0, long x1, long x2, long x3) {
- this.x0 = x0;
+ 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, 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);
- }
+ // 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
+ * Creates a new instance of {@link Xoshiro256StarStar} using the
* specified {@code long} value as the initial seed. Instances of
- * {@code Xoshiro256StarStar} created with the same seed in the same
+ * {@link 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));
+ // 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
+ * Creates a new instance of {@link 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));
+ // Using GOLDEN_RATIO_64 here gives us a good Weyl sequence of values.
+ this(DEFAULT_GEN.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
+ * Creates a new instance of {@link Xoshiro256StarStar} using the specified array of
+ * initial seed bytes. Instances of {@link 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];
+ // 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;
@@ -222,64 +222,75 @@
/* ---------------- public methods ---------------- */
- public Xoshiro256StarStar copy() { return new Xoshiro256StarStar(x0, x1, x2, x3); }
+ 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 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 BigInteger period() {
+ return PERIOD;
+ }
-
- public double defaultJumpDistance() { return 0x1.0p64; }
- public double defaultLeapDistance() { return 0x1.0p96; }
+ public double defaultJumpDistance() {
+ return 0x1.0p64;
+ }
+
+ public double defaultLeapDistance() {
+ return 0x1.0p96;
+ }
private static final long[] JUMP_TABLE = {
- 0x180ec6d33cfd0abaL, 0xd5a61266f0c9392cL, 0xa9582618e03fc9aaL, 0x39abdc4529b1661cL };
-
+ 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. */
+ 0x76e15d3efefdcbbfL, 0xc5004e441c522fb3L, 0x77710069854ee241L, 0x39109bb02acbe635L };
- 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. */
+ /**
+ * 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);
+ }
- public void leap() { jumpAlgorithm(LEAP_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;
- }
+ 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;
+ }
}
}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.base/share/classes/java/util/random/package-info.java Thu Jun 27 18:30:27 2019 -0300
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) 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 info goes here.
+ *
+ * @since 14
+ */
+
+ package java.util.random;
+
+
--- a/src/java.base/share/classes/module-info.java Thu Jun 27 18:02:51 2019 -0300
+++ b/src/java.base/share/classes/module-info.java Thu Jun 27 18:30:27 2019 -0300
@@ -113,6 +113,7 @@
exports java.util.concurrent.locks;
exports java.util.function;
exports java.util.jar;
+ exports java.util.random;
exports java.util.regex;
exports java.util.spi;
exports java.util.stream;
@@ -349,6 +350,7 @@
uses java.time.chrono.AbstractChronology;
uses java.time.chrono.Chronology;
uses java.time.zone.ZoneRulesProvider;
+ uses java.util.random.RandomNumberGenerator;
uses java.util.spi.CalendarDataProvider;
uses java.util.spi.CalendarNameProvider;
uses java.util.spi.CurrencyNameProvider;
@@ -372,4 +374,19 @@
provides java.nio.file.spi.FileSystemProvider with
jdk.internal.jrtfs.JrtFileSystemProvider;
+
+ provides java.util.random.RandomNumberGenerator with
+ java.util.random.L128X256MixRandom,
+ java.util.random.L32X64MixRandom,
+ java.util.random.L64X1024MixRandom,
+ java.util.random.L64X1024Random,
+ java.util.random.L64X128MixRandom,
+ java.util.random.L64X128Random,
+ java.util.random.L64X256MixRandom,
+ java.util.random.L64X256Random,
+ java.util.random.MRG32k3a,
+ java.util.random.Xoroshiro128Plus,
+ java.util.random.Xoroshiro128StarStar,
+ java.util.random.Xoshiro256StarStar;
+
}