1 /*
2  * Copyright (c) 2020, 2022, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.  Oracle designates this
8  * particular file as subject to the "Classpath" exception as provided
9  * by Oracle in the LICENSE file that accompanied this code.
10  *
11  * This code is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14  * version 2 for more details (a copy is included in the LICENSE file that
15  * accompanied this code).
16  *
17  * You should have received a copy of the GNU General Public License version
18  * 2 along with this work; if not, write to the Free Software Foundation,
19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20  *
21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22  * or visit www.oracle.com if you need additional information or have any
23  * questions.
24  */
25 
26 package jdk.internal.util.random;
27 
28 import java.lang.annotation.*;
29 import java.math.BigInteger;
30 import java.util.Objects;
31 import java.util.Random;
32 import java.util.function.Consumer;
33 import java.util.function.DoubleConsumer;
34 import java.util.function.IntConsumer;
35 import java.util.function.LongConsumer;
36 import java.util.random.RandomGenerator;
37 import java.util.random.RandomGenerator.SplittableGenerator;
38 import java.util.Spliterator;
39 import java.util.stream.DoubleStream;
40 import java.util.stream.IntStream;
41 import java.util.stream.LongStream;
42 import java.util.stream.Stream;
43 import java.util.stream.StreamSupport;
44 
45 /**
46  * Low-level utility methods helpful for implementing pseudorandom number
47  * generators.
48  *
49  * <p> This class is mostly for library writers creating specific
50  * implementations of the interface {@link RandomGenerator}. As an
51  * internal package it is not intended for general use.
52  *
53  * @since 17
54  */
55 public class RandomSupport {
56     /**
57      * Annotation providing RandomGenerator properties.
58      */
59     @Retention(RetentionPolicy.RUNTIME)
60     @Target(ElementType.TYPE)
61     public @interface RandomGeneratorProperties {
62         /**
63          * Name of algorithm.
64          */
name()65         String name();
66 
67         /**
68          * Category of algorithm.
69          */
group()70         String group() default "Legacy";
71 
72         /**
73          * Algorithm period defined as:
74          *
75          * BigInteger.ONE.shiftLeft(i)
76          *               .subtract(j)
77          *               .shiftLeft(k)
78          */
i()79         int i() default 0;
j()80         int j() default 0;
k()81         int k() default 0;
82 
83         /**
84          * The equidistribution of the algorithm.
85          */
equidistribution()86         int equidistribution() default Integer.MAX_VALUE;
87 
88         /**
89          * Is the algorithm based on entropy (true random.)
90          */
isStochastic()91         boolean isStochastic() default false;
92 
93         /**
94          * Is the algorithm assisted by hardware (fast true random.)
95          */
isHardware()96         boolean isHardware() default false;
97     }
98 
99     /*
100      * Implementation Overview.
101      *
102      * This class provides utility methods and constants frequently
103      * useful in the implementation of pseudorandom number generators
104      * that satisfy the interface {@link RandomGenerator}.
105      *
106      * File organization: First some message strings, then the main
107      * public methods, followed by a non-public base spliterator class.
108      */
109 
110     // IllegalArgumentException messages
111     public static final String BAD_SIZE = "size must be non-negative";
112     public static final String BAD_DISTANCE = "jump distance must be finite, positive, and an exact integer";
113     public static final String BAD_BOUND = "bound must be positive";
114     public static final String BAD_FLOATING_BOUND = "bound must be finite and positive";
115     public static final String BAD_RANGE = "bound must be greater than origin";
116 
117     /* ---------------- explicit constructor ---------------- */
118 
119     /**
120      * Explicit constructor.
121      */
RandomSupport()122     protected RandomSupport() {
123     }
124 
125     /* ---------------- public methods ---------------- */
126 
127     /**
128      * Check a {@code long} proposed stream size for validity.
129      *
130      * @param streamSize the proposed stream size
131      *
132      * @throws IllegalArgumentException if {@code streamSize} is negative
133      */
checkStreamSize(long streamSize)134     public static void checkStreamSize(long streamSize) {
135         if (streamSize < 0L) {
136             throw new IllegalArgumentException(BAD_SIZE);
137         }
138     }
139 
140     /**
141      * Checks a {@code float} upper bound value for validity.
142      *
143      * @param bound the upper bound (exclusive)
144      *
145      * @throws IllegalArgumentException if {@code bound} fails to be positive and finite
146      */
checkBound(float bound)147     public static void checkBound(float bound) {
148         if (!(bound > 0.0 && bound < Float.POSITIVE_INFINITY)) {
149             throw new IllegalArgumentException(BAD_FLOATING_BOUND);
150         }
151     }
152 
153     /**
154      * Checks a {@code double} upper bound value for validity.
155      *
156      * @param bound the upper bound (exclusive)
157      *
158      * @throws IllegalArgumentException if {@code bound} fails to be positive and finite
159      */
checkBound(double bound)160     public static void checkBound(double bound) {
161         if (!(bound > 0.0 && bound < Double.POSITIVE_INFINITY)) {
162             throw new IllegalArgumentException(BAD_FLOATING_BOUND);
163         }
164     }
165 
166     /**
167      * Checks an {@code int} upper bound value for validity.
168      *
169      * @param bound the upper bound (exclusive)
170      *
171      * @throws IllegalArgumentException if {@code bound} is not positive
172      */
checkBound(int bound)173     public static void checkBound(int bound) {
174         if (bound <= 0) {
175             throw new IllegalArgumentException(BAD_BOUND);
176         }
177     }
178 
179     /**
180      * Checks a {@code long} upper bound value for validity.
181      *
182      * @param bound the upper bound (exclusive)
183      *
184      * @throws IllegalArgumentException if {@code bound} is not positive
185      */
checkBound(long bound)186     public static void checkBound(long bound) {
187         if (bound <= 0) {
188             throw new IllegalArgumentException(BAD_BOUND);
189         }
190     }
191 
192     /**
193      * Checks a {@code float} range for validity.
194      *
195      * @param origin the least value (inclusive) in the range
196      * @param bound  the upper bound (exclusive) of the range
197      *
198      * @throws IllegalArgumentException if {@code origin} is not finite, {@code bound} is not finite,
199      *                                  or {@code bound - origin} is not finite
200      */
checkRange(float origin, float bound)201     public static void checkRange(float origin, float bound) {
202         if (!(origin < bound && (bound - origin) < Float.POSITIVE_INFINITY)) {
203             throw new IllegalArgumentException(BAD_RANGE);
204         }
205     }
206 
207     /**
208      * Checks a {@code double} range for validity.
209      *
210      * @param origin the least value (inclusive) in the range
211      * @param bound  the upper bound (exclusive) of the range
212      *
213      * @throws IllegalArgumentException if {@code origin} is not finite, {@code bound} is not finite,
214      *                                  or {@code bound - origin} is not finite
215      */
checkRange(double origin, double bound)216     public static void checkRange(double origin, double bound) {
217         if (!(origin < bound && (bound - origin) < Double.POSITIVE_INFINITY)) {
218             throw new IllegalArgumentException(BAD_RANGE);
219         }
220     }
221 
222     /**
223      * Checks an {@code int} range for validity.
224      *
225      * @param origin the least value that can be returned
226      * @param bound  the upper bound (exclusive) for the returned value
227      *
228      * @throws IllegalArgumentException if {@code origin} is greater than or equal to {@code bound}
229      */
checkRange(int origin, int bound)230     public static void checkRange(int origin, int bound) {
231         if (origin >= bound) {
232             throw new IllegalArgumentException(BAD_RANGE);
233         }
234     }
235 
236     /**
237      * Checks a {@code long} range for validity.
238      *
239      * @param origin the least value that can be returned
240      * @param bound  the upper bound (exclusive) for the returned value
241      *
242      * @throws IllegalArgumentException if {@code origin} is greater than or equal to {@code bound}
243      */
checkRange(long origin, long bound)244     public static void checkRange(long origin, long bound) {
245         if (origin >= bound) {
246             throw new IllegalArgumentException(BAD_RANGE);
247         }
248     }
249 
250     /**
251      * Given an array of seed bytes of any length, construct an array of
252      * {@code long} seed values of length {@code n}, such that the last
253      * {@code z} values are not all zero.
254      *
255      * @param seed an array of {@code byte} values
256      * @param n the length of the result array (should be nonnegative)
257      * @param z the number of trailing result elements that are required
258      *        to be not all zero (should be nonnegative but not larger
259      *        than {@code n})
260      *
261      * @return an array of length {@code n} containing {@code long} seed values
262      */
convertSeedBytesToLongs(byte[] seed, int n, int z)263     public static long[] convertSeedBytesToLongs(byte[] seed, int n, int z) {
264         final long[] result = new long[n];
265         final int m = Math.min(seed.length, n << 3);
266         // Distribute seed bytes into the words to be formed.
267         for (int j = 0; j < m; j++) {
268             result[j>>3] = (result[j>>3] << 8) | seed[j];
269         }
270         // If there aren't enough seed bytes for all the words we need,
271         // use a SplitMix-style PRNG to fill in the rest.
272         long v = result[0];
273         for (int j = (m + 7) >> 3; j < n; j++) {
274             result[j] = mixMurmur64(v += SILVER_RATIO_64);
275         }
276         // Finally, we need to make sure the last z words are not all zero.
277         search: {
278             for (int j = n - z; j < n; j++) {
279                 if (result[j] != 0) break search;
280             }
281             // If they are, fill in using a SplitMix-style PRNG.
282             // Using "& ~1L" in the next line defends against the case z==1
283             // by guaranteeing that the first generated value will be nonzero.
284             long w = result[0] & ~1L;
285             for (int j = n - z; j < n; j++) {
286                 result[j] = mixMurmur64(w += SILVER_RATIO_64);
287             }
288         }
289 
290         return result;
291     }
292 
293     /**
294      * Given an array of seed bytes of any length, construct an array of
295      * {@code int} seed values of length {@code n}, such that the last {@code z}
296      * values are not all zero.
297      *
298      * @param seed an array of {@code byte} values
299      * @param n the length of the result array (should be nonnegative)
300      * @param z the number of trailing result elements that are required
301      *        to be not all zero (should be nonnegative but not larger
302      *        than {@code n})
303      *
304      * @return an array of length {@code n} containing {@code int} seed values
305      */
convertSeedBytesToInts(byte[] seed, int n, int z)306     public static int[] convertSeedBytesToInts(byte[] seed, int n, int z) {
307         final int[] result = new int[n];
308         final int m = Math.min(seed.length, n << 2);
309         // Distribute seed bytes into the words to be formed.
310         for (int j = 0; j < m; j++) {
311             result[j>>2] = (result[j>>2] << 8) | seed[j];
312         }
313         // If there aren't enough seed bytes for all the words we need,
314         // use a SplitMix-style PRNG to fill in the rest.
315         int v = result[0];
316         for (int j = (m + 3) >> 2; j < n; j++) {
317             result[j] = mixMurmur32(v += SILVER_RATIO_32);
318         }
319         // Finally, we need to make sure the last z words are not all zero.
320         search: {
321             for (int j = n - z; j < n; j++) {
322                 if (result[j] != 0) break search;
323             }
324             // If they are, fill in using a SplitMix-style PRNG.
325             // Using "& ~1" in the next line defends against the case z==1
326             // by guaranteeing that the first generated value will be nonzero.
327             int w = result[0] & ~1;
328             for (int j = n - z; j < n; j++) {
329                 result[j] = mixMurmur32(w += SILVER_RATIO_32);
330             }
331         }
332         return result;
333     }
334 
335     /*
336      * Bounded versions of nextX methods used by streams, as well as
337      * the public nextX(origin, bound) methods.  These exist mainly to
338      * avoid the need for multiple versions of stream spliterators
339      * across the different exported forms of streams.
340      */
341 
342     /**
343      * This is the form of {@link RandomGenerator#nextLong() nextLong}() used by
344      * a {@link LongStream} {@link Spliterator} and by the public method
345      * {@link RandomGenerator#nextLong(long, long) nextLong}(origin, bound). If
346      * {@code origin} is greater than {@code bound}, then this method simply
347      * calls the unbounded version of
348      * {@link RandomGenerator#nextLong() nextLong}(), choosing pseudorandomly
349      * from among all 2<sup>64</sup> possible {@code long} values}, and
350      * otherwise uses one or more calls to
351      * {@link RandomGenerator#nextLong() nextLong}() to choose a value
352      * pseudorandomly from the possible values between {@code origin}
353      * (inclusive) and {@code bound} (exclusive).
354      *
355      * @implNote This method first calls {@code nextLong()} to obtain
356      * a {@code long} value that is assumed to be pseudorandomly
357      * chosen uniformly and independently from the 2<sup>64</sup>
358      * possible {@code long} values (that is, each of the 2<sup>64</sup>
359      * possible long values is equally likely to be chosen).
360      * Under some circumstances (when the specified range is not
361      * a power of 2), {@code nextLong()} may be called additional times
362      * to ensure that that the values in the specified range are
363      * equally likely to be chosen (provided the assumption holds).
364      *
365      * The implementation considers four cases:
366      * <ol>
367      *
368      * <li> If the {@code} bound} is less than or equal to the {@code origin}
369      * (indicated an unbounded form), the 64-bit {@code long} value obtained
370      * from {@link RandomGenerator#nextLong() nextLong}() is returned directly.
371      * </li>
372      *
373      * <li> Otherwise, if the length <i>n</i> of the specified range is an
374      * exact power of two 2<sup><i>m</i></sup> for some integer
375      *      <i>m</i>, then return the sum of {@code origin} and the
376      *      <i>m</i> lowest-order bits of the value from {@code nextLong()}.
377      * </li>
378      *
379      * <li> Otherwise, if the length <i>n</i> of the specified range
380      * is less than 2<sup>63</sup>, then the basic idea is to use the remainder
381      * modulo <i>n</i> of the value from
382      * {@link RandomGenerator#nextLong() nextLong}(), but with this approach
383      * some values will be over-represented. Therefore a loop is used to avoid
384      * potential bias by rejecting candidates that are too large. Assuming that
385      * the results from {@link RandomGenerator#nextLong() nextLong}() are truly
386      * chosen uniformly and independently, the expected number of iterations
387      * will be somewhere between 1 and 2, depending on the precise value of
388      * <i>n</i>.</li>
389      *
390      * <li> Otherwise, the length <i>n</i> of the specified range
391      * cannot be represented as a positive {@code long} value. A loop repeatedly
392      * calls {@link RandomGenerator#nextLong() nextLong}() until obtaining a
393      * suitable candidate, Again, the expected number of iterations is less than
394      * 2.</li>
395      *
396      * </ol>
397      *
398      * @param rng a random number generator to be used as a
399      *        source of pseudorandom {@code long} values
400      * @param origin the least value that can be produced,
401      *        unless greater than or equal to {@code bound}
402      * @param bound the upper bound (exclusive), unless {@code origin}
403      *        is greater than or equal to {@code bound}
404      *
405      * @return a pseudorandomly chosen {@code long} value,
406      *         which will be between {@code origin} (inclusive) and
407      *         {@code bound} exclusive unless {@code origin}
408      *         is greater than or equal to {@code bound}
409      */
boundedNextLong(RandomGenerator rng, long origin, long bound)410     public static long boundedNextLong(RandomGenerator rng, long origin, long bound) {
411         long r = rng.nextLong();
412         if (origin < bound) {
413             // It's not case (1).
414             final long n = bound - origin;
415             final long m = n - 1;
416             if ((n & m) == 0L) {
417                 // It is case (2): length of range is a power of 2.
418                 r = (r & m) + origin;
419             } else if (n > 0L) {
420                 // It is case (3): need to reject over-represented candidates.
421                 /* This loop takes an unlovable form (but it works):
422                    because the first candidate is already available,
423                    we need a break-in-the-middle construction,
424                    which is concisely but cryptically performed
425                    within the while-condition of a body-less for loop. */
426                 for (long u = r >>> 1;            // ensure nonnegative
427                      u + m - (r = u % n) < 0L;    // rejection check
428                      u = rng.nextLong() >>> 1) // retry
429                     ;
430                 r += origin;
431             }
432             else {
433                 // It is case (4): length of range not representable as long.
434                 while (r < origin || r >= bound)
435                     r = rng.nextLong();
436             }
437         }
438         return r;
439     }
440 
441     /**
442      * This is the form of {@link RandomGenerator#nextLong() nextLong}() used by
443      * the public method {@link RandomGenerator#nextLong(long) nextLong}(bound).
444      * This is essentially a version of
445      * {@link RandomSupport#boundedNextLong(RandomGenerator, long, long) boundedNextLong}(rng, origin, bound)
446      * that has been specialized for the case where the {@code origin} is zero
447      * and the {@code bound} is greater than zero. The value returned is chosen
448      * pseudorandomly from nonnegative integer values less than {@code bound}.
449      *
450      * @implNote This method first calls {@code nextLong()} to obtain
451      * a {@code long} value that is assumed to be pseudorandomly
452      * chosen uniformly and independently from the 2<sup>64</sup>
453      * possible {@code long} values (that is, each of the 2<sup>64</sup>
454      * possible long values is equally likely to be chosen).
455      * Under some circumstances (when the specified range is not
456      * a power of 2), {@code nextLong()} may be called additional times
457      * to ensure that that the values in the specified range are
458      * equally likely to be chosen (provided the assumption holds).
459      *
460      * The implementation considers two cases:
461      * <ol>
462      *
463      * <li> If {@code bound} is an exact power of two 2<sup><i>m</i></sup>
464      * for some integer <i>m</i>, then return the sum of {@code origin} and the
465      * <i>m</i> lowest-order bits of the value from
466      * {@link RandomGenerator#nextLong() nextLong}().</li>
467      *
468      * <li> Otherwise, the basic idea is to use the remainder modulo
469      *      <i>bound</i> of the value from {@code nextLong()},
470      * but with this approach some values will be over-represented. Therefore a
471      * loop is used to avoid potential bias by rejecting candidates that vare
472      * too large. Assuming that the results from
473      * {@link RandomGenerator#nextLong() nextLong}() are truly chosen uniformly
474      * and independently, the expected number of iterations will be somewhere
475      * between 1 and 2, depending on the precise value of <i>bound</i>.</li>
476      *
477      * </ol>
478      *
479      * @param rng a random number generator to be used as a
480      *        source of pseudorandom {@code long} values
481      * @param bound the upper bound (exclusive); must be greater than zero
482      *
483      * @return a pseudorandomly chosen {@code long} value
484      */
boundedNextLong(RandomGenerator rng, long bound)485     public static long boundedNextLong(RandomGenerator rng, long bound) {
486         // Specialize boundedNextLong for origin == 0, bound > 0
487         final long m = bound - 1;
488         long r = rng.nextLong();
489         if ((bound & m) == 0L) {
490             // The bound is a power of 2.
491             r &= m;
492         } else {
493             // Must reject over-represented candidates
494             /* This loop takes an unlovable form (but it works):
495                because the first candidate is already available,
496                we need a break-in-the-middle construction,
497                which is concisely but cryptically performed
498                within the while-condition of a body-less for loop. */
499             for (long u = r >>> 1;
500                  u + m - (r = u % bound) < 0L;
501                  u = rng.nextLong() >>> 1)
502                 ;
503         }
504         return r;
505     }
506 
507     /**
508      * This is the form of {@link RandomGenerator#nextInt() nextInt}() used by
509      * an {@link IntStream} {@link Spliterator} and by the public method
510      * {@link RandomGenerator#nextInt(int, int) nextInt}(origin, bound). If
511      * {@code origin} is greater than {@code bound}, then this method simply
512      * calls the unbounded version of
513      * {@link RandomGenerator#nextInt() nextInt}(), choosing pseudorandomly
514      * from among all 2<sup>64</sup> possible {@code int} values}, and otherwise
515      * uses one or more calls to {@link RandomGenerator#nextInt() nextInt}() to
516      * choose a value pseudorandomly from the possible values between
517      * {@code origin} (inclusive) and {@code bound} (exclusive).
518      *
519      * @param rng a random number generator to be used as a
520      *        source of pseudorandom {@code int} values
521      * @param origin the least value that can be produced,
522      *        unless greater than or equal to {@code bound}
523      * @param bound the upper bound (exclusive), unless {@code origin}
524      *        is greater than or equal to {@code bound}
525      *
526      * @return a pseudorandomly chosen {@code int} value,
527      *         which will be between {@code origin} (inclusive) and
528      *         {@code bound} exclusive unless {@code origin}
529      *         is greater than or equal to {@code bound}
530      *
531      * @implNote The implementation of this method is identical to
532      *           the implementation of {@code nextLong(origin, bound)}
533      *           except that {@code int} values and the {@code nextInt()}
534      *           method are used rather than {@code long} values and the
535      *           {@code nextLong()} method.
536      */
boundedNextInt(RandomGenerator rng, int origin, int bound)537     public static int boundedNextInt(RandomGenerator rng, int origin, int bound) {
538         int r = rng.nextInt();
539         if (origin < bound) {
540             // It's not case (1).
541             final int n = bound - origin;
542             final int m = n - 1;
543             if ((n & m) == 0) {
544                 // It is case (2): length of range is a power of 2.
545                 r = (r & m) + origin;
546             } else if (n > 0) {
547                 // It is case (3): need to reject over-represented candidates.
548                 for (int u = r >>> 1;
549                      u + m - (r = u % n) < 0;
550                      u = rng.nextInt() >>> 1)
551                     ;
552                 r += origin;
553             }
554             else {
555                 // It is case (4): length of range not representable as long.
556                 while (r < origin || r >= bound) {
557                     r = rng.nextInt();
558                 }
559             }
560         }
561         return r;
562     }
563 
564     /**
565      * This is the form of {@link RandomGenerator#nextInt() nextInt}() used by
566      * the public method {@link RandomGenerator#nextInt(int) nextInt}(bound).
567      * This is essentially a version of
568      * {@link RandomSupport#boundedNextInt(RandomGenerator, int, int) boundedNextInt}(rng, origin, bound)
569      * that has been specialized for the case where the {@code origin} is zero
570      * and the {@code bound} is greater than zero. The value returned is chosen
571      * pseudorandomly from nonnegative integer values less than {@code bound}.
572      *
573      * @param rng a random number generator to be used as a
574      *        source of pseudorandom {@code long} values
575      * @param bound the upper bound (exclusive); must be greater than zero
576      *
577      * @return a pseudorandomly chosen {@code long} value
578      *
579      * @implNote The implementation of this method is identical to
580      *           the implementation of {@code nextLong(bound)}
581      *           except that {@code int} values and the {@code nextInt()}
582      *           method are used rather than {@code long} values and the
583      *           {@code nextLong()} method.
584      */
boundedNextInt(RandomGenerator rng, int bound)585     public static int boundedNextInt(RandomGenerator rng, int bound) {
586         // Specialize boundedNextInt for origin == 0, bound > 0
587         final int m = bound - 1;
588         int r = rng.nextInt();
589         if ((bound & m) == 0) {
590             // The bound is a power of 2.
591             r &= m;
592         } else {
593             // Must reject over-represented candidates
594             for (int u = r >>> 1;
595                  u + m - (r = u % bound) < 0;
596                  u = rng.nextInt() >>> 1)
597                 ;
598         }
599         return r;
600     }
601 
602     /**
603      * This is the form of {@link RandomGenerator#nextDouble() nextDouble}()
604      * used by a {@link DoubleStream} {@link Spliterator} and by the public
605      * method
606      * {@link RandomGenerator#nextDouble(double, double) nextDouble}(origin, bound).
607      * If {@code origin} is greater than {@code bound}, then this method simply
608      * calls the unbounded version of
609      * {@link RandomGenerator#nextDouble() nextDouble}(), and otherwise scales
610      * and translates the result of a call to
611      * {@link RandomGenerator#nextDouble() nextDouble}() so that it lies between
612      * {@code origin} (inclusive) and {@code bound} (exclusive).
613      *
614      * @implNote The implementation considers two cases:
615      * <ol>
616      *
617      * <li> If the {@code bound} is less than or equal to the {@code origin}
618      * (indicated an unbounded form), the 64-bit {@code double} value obtained
619      * from {@link RandomGenerator#nextDouble() nextDouble}() is returned
620      * directly.
621      *
622      * <li> Otherwise, the result of a call to {@code nextDouble} is
623      * multiplied by {@code (bound - origin)}, then {@code origin} is added, and
624      * then if this this result is not less than {@code bound} (which can
625      * sometimes occur because of rounding), it is replaced with the largest
626      * {@code double} value that is less than {@code bound}.
627      *
628      * </ol>
629      *
630      * @param rng a random number generator to be used as a
631      *        source of pseudorandom {@code double} values
632      * @param origin the least value that can be produced,
633      *        unless greater than or equal to {@code bound}; must be finite
634      * @param bound the upper bound (exclusive), unless {@code origin}
635      *        is greater than or equal to {@code bound}; must be finite
636      * @return a pseudorandomly chosen {@code double} value,
637      *         which will be between {@code origin} (inclusive) and
638      *         {@code bound} exclusive unless {@code origin}
639      *         is greater than or equal to {@code bound},
640      *         in which case it will be between 0.0 (inclusive)
641      *         and 1.0 (exclusive)
642      */
boundedNextDouble(RandomGenerator rng, double origin, double bound)643     public static double boundedNextDouble(RandomGenerator rng, double origin, double bound) {
644         double r = rng.nextDouble();
645         if (origin < bound) {
646             r = r * (bound - origin) + origin;
647             if (r >= bound)  // may need to correct a rounding problem
648                 r = Math.nextAfter(bound, origin);
649         }
650         return r;
651     }
652 
653     /**
654      * This is the form of {@link RandomGenerator#nextDouble() nextDouble}()
655      * used by the public method
656      * {@link RandomGenerator#nextDouble(double) nextDouble}(bound). This is
657      * essentially a version of
658      * {@link RandomSupport#boundedNextDouble(RandomGenerator, double, double) boundedNextDouble}(rng, origin, bound)
659      * that has been specialized for the case where the {@code origin} is zero
660      * and the {@code bound} is greater than zero.
661      *
662      * @implNote The result of a call to {@code nextDouble} is
663      *      multiplied by {@code bound}, and then if this result is
664      *      not less than {@code bound} (which can sometimes occur
665      *      because of rounding), it is replaced with the largest
666      *      {@code double} value that is less than {@code bound}.
667      *
668      * @param rng a random number generator to be used as a
669      *        source of pseudorandom {@code double} values
670      * @param bound the upper bound (exclusive); must be finite and
671      *        greater than zero
672      * @return a pseudorandomly chosen {@code double} value
673      *         between zero (inclusive) and {@code bound} (exclusive)
674      */
boundedNextDouble(RandomGenerator rng, double bound)675     public static double boundedNextDouble(RandomGenerator rng, double bound) {
676         // Specialize boundedNextDouble for origin == 0, bound > 0
677         double r = rng.nextDouble();
678         r = r * bound;
679         if (r >= bound)  // may need to correct a rounding problem
680             r = Math.nextDown(bound);
681         return r;
682     }
683 
684     /**
685      * This is the form of {@link RandomGenerator#nextFloat() nextFloat}() used
686      * by a {@link Stream<Float>} {@link Spliterator} (if there were any) and by
687      * the public method
688      * {@link RandomGenerator#nextFloat(float, float) nextFloat}(origin, bound).
689      * If {@code origin} is greater than {@code bound}, then this method simply
690      * calls the unbounded version of
691      * {@link RandomGenerator#nextFloat() nextFloat}(), and otherwise scales and
692      * translates the result of a call to
693      * {@link RandomGenerator#nextFloat() nextFloat}() so that it lies between
694      * {@code origin} (inclusive) and {@code bound} (exclusive).
695      *
696      * @implNote The implementation of this method is identical to
697      *     the implementation of {@code nextDouble(origin, bound)}
698      *     except that {@code float} values and the {@code nextFloat()}
699      *     method are used rather than {@code double} values and the
700      *     {@code nextDouble()} method.
701      *
702      * @param rng a random number generator to be used as a
703      *        source of pseudorandom {@code float} values
704      * @param origin the least value that can be produced,
705      *        unless greater than or equal to {@code bound}; must be finite
706      * @param bound the upper bound (exclusive), unless {@code origin}
707      *        is greater than or equal to {@code bound}; must be finite
708      * @return a pseudorandomly chosen {@code float} value,
709      *         which will be between {@code origin} (inclusive) and
710      *         {@code bound} exclusive unless {@code origin}
711      *         is greater than or equal to {@code bound},
712      *         in which case it will be between 0.0 (inclusive)
713      *         and 1.0 (exclusive)
714      */
boundedNextFloat(RandomGenerator rng, float origin, float bound)715     public static float boundedNextFloat(RandomGenerator rng, float origin, float bound) {
716         float r = rng.nextFloat();
717         if (origin < bound) {
718             r = r * (bound - origin) + origin;
719             if (r >= bound) // may need to correct a rounding problem
720                 r = Float.intBitsToFloat(Float.floatToIntBits(bound) - 1);
721         }
722         return r;
723     }
724 
725     /**
726      * This is the form of {@link RandomGenerator#nextFloat() nextFloat}() used
727      * by the public method
728      * {@link RandomGenerator#nextFloat(float) nextFloat}(bound). This is
729      * essentially a version of
730      * {@link RandomSupport#boundedNextFloat(RandomGenerator, float, float) boundedNextFloat}(rng, origin, bound)
731      * that has been specialized for the case where the {@code origin} is zero
732      * and the {@code bound} is greater than zero.
733      *
734      * @implNote The implementation of this method is identical to
735      *     the implementation of {@code nextDouble(bound)}
736      *     except that {@code float} values and the {@code nextFloat()}
737      *     method are used rather than {@code double} values and the
738      *     {@code nextDouble()} method.
739      *
740      * @param rng a random number generator to be used as a
741      *        source of pseudorandom {@code float} values
742      * @param bound the upper bound (exclusive); must be finite and
743      *        greater than zero
744      * @return a pseudorandomly chosen {@code float} value
745      *         between zero (inclusive) and {@code bound} (exclusive)
746      */
boundedNextFloat(RandomGenerator rng, float bound)747     public static float boundedNextFloat(RandomGenerator rng, float bound) {
748         // Specialize boundedNextFloat for origin == 0, bound > 0
749         float r = rng.nextFloat();
750         r = r * bound;
751         if (r >= bound) // may need to correct a rounding problem
752             r = Float.intBitsToFloat(Float.floatToIntBits(bound) - 1);
753         return r;
754     }
755 
756     // The following decides which of two strategies initialSeed() will use.
secureRandomSeedRequested()757     private static boolean secureRandomSeedRequested() {
758         @SuppressWarnings("removal")
759         String pp = java.security.AccessController.doPrivileged(
760                 new sun.security.action.GetPropertyAction(
761                         "java.util.secureRandomSeed"));
762         return (pp != null && pp.equalsIgnoreCase("true"));
763     }
764 
765     private static final boolean useSecureRandomSeed = secureRandomSeedRequested();
766 
767     /**
768      * Returns a {@code long} value (chosen from some machine-dependent entropy
769      * source) that may be useful for initializing a source of seed values for
770      * instances of {@link RandomGenerator} created by zero-argument
771      * constructors. (This method should
772      * <i>not</i> be called repeatedly, once per constructed
773      * object; at most it should be called once per class.)
774      *
775      * @return a {@code long} value, randomly chosen using
776      *         appropriate environmental entropy
777      */
initialSeed()778     public static long initialSeed() {
779         if (useSecureRandomSeed) {
780             byte[] seedBytes = java.security.SecureRandom.getSeed(8);
781             long s = (long)(seedBytes[0]) & 0xffL;
782             for (int i = 1; i < 8; ++i)
783                 s = (s << 8) | ((long)(seedBytes[i]) & 0xffL);
784             return s;
785         }
786         return (mixStafford13(System.currentTimeMillis()) ^
787                 mixStafford13(System.nanoTime()));
788     }
789 
790     /**
791      * The first 32 bits of the golden ratio (1+sqrt(5))/2, forced to be odd.
792      * Useful for producing good Weyl sequences or as an arbitrary nonzero odd
793      * value.
794      */
795     public static final int  GOLDEN_RATIO_32 = 0x9e3779b9;
796 
797     /**
798      * The first 64 bits of the golden ratio (1+sqrt(5))/2, forced to be odd.
799      * Useful for producing good Weyl sequences or as an arbitrary nonzero odd
800      * value.
801      */
802     public static final long GOLDEN_RATIO_64 = 0x9e3779b97f4a7c15L;
803 
804     /**
805      * The first 32 bits of the silver ratio 1+sqrt(2), forced to be odd. Useful
806      * for producing good Weyl sequences or as an arbitrary nonzero odd value.
807      */
808     public static final int  SILVER_RATIO_32 = 0x6A09E667;
809 
810     /**
811      * The first 64 bits of the silver ratio 1+sqrt(2), forced to be odd. Useful
812      * for producing good Weyl sequences or as an arbitrary nonzero odd value.
813      */
814     public static final long SILVER_RATIO_64 = 0x6A09E667F3BCC909L;
815 
816     /**
817      * Computes the 64-bit mixing function for MurmurHash3. This is a 64-bit
818      * hashing function with excellent avalanche statistics.
819      * https://github.com/aappleby/smhasher/wiki/MurmurHash3
820      *
821      * <p> Note that if the argument {@code z} is 0, the result is 0.
822      *
823      * @param z any long value
824      *
825      * @return the result of hashing z
826      */
mixMurmur64(long z)827     public static long mixMurmur64(long z) {
828         z = (z ^ (z >>> 33)) * 0xff51afd7ed558ccdL;
829         z = (z ^ (z >>> 33)) * 0xc4ceb9fe1a85ec53L;
830         return z ^ (z >>> 33);
831     }
832 
833     /**
834      * Computes Stafford variant 13 of the 64-bit mixing function for
835      * MurmurHash3. This is a 64-bit hashing function with excellent avalanche
836      * statistics.
837      * http://zimbry.blogspot.com/2011/09/better-bit-mixing-improving-on.html
838      *
839      * <p> Note that if the argument {@code z} is 0, the result is 0.
840      *
841      * @param z any long value
842      *
843      * @return the result of hashing z
844      */
mixStafford13(long z)845     public static long mixStafford13(long z) {
846         z = (z ^ (z >>> 30)) * 0xbf58476d1ce4e5b9L;
847         z = (z ^ (z >>> 27)) * 0x94d049bb133111ebL;
848         return z ^ (z >>> 31);
849     }
850 
851     /**
852      * Computes Doug Lea's 64-bit mixing function. This is a 64-bit hashing
853      * function with excellent avalanche statistics. It has the advantages of
854      * using the same multiplicative constant twice and of using only 32-bit
855      * shifts.
856      *
857      * <p> Note that if the argument {@code z} is 0, the result is 0.
858      *
859      * @param z any long value
860      *
861      * @return the result of hashing z
862      */
mixLea64(long z)863     public static long mixLea64(long z) {
864         z = (z ^ (z >>> 32)) * 0xdaba0b6eb09322e3L;
865         z = (z ^ (z >>> 32)) * 0xdaba0b6eb09322e3L;
866         return z ^ (z >>> 32);
867     }
868 
869     /**
870      * Computes the 32-bit mixing function for MurmurHash3. This is a 32-bit
871      * hashing function with excellent avalanche statistics.
872      * https://github.com/aappleby/smhasher/wiki/MurmurHash3
873      *
874      * <p> Note that if the argument {@code z} is 0, the result is 0.
875      *
876      * @param z any long value
877      *
878      * @return the result of hashing z
879      */
mixMurmur32(int z)880     public static int mixMurmur32(int z) {
881         z = (z ^ (z >>> 16)) * 0x85ebca6b;
882         z = (z ^ (z >>> 13)) * 0xc2b2ae35;
883         return z ^ (z >>> 16);
884     }
885 
886     /**
887      * Computes Doug Lea's 32-bit mixing function. This is a 32-bit hashing
888      * function with excellent avalanche statistics. It has the advantages of
889      * using the same multiplicative constant twice and of using only 16-bit
890      * shifts.
891      *
892      * <p> Note that if the argument {@code z} is 0, the result is 0.
893      *
894      * @param z any long value
895      *
896      * @return the result of hashing z
897      */
mixLea32(int z)898     public static int mixLea32(int z) {
899         z = (z ^ (z >>> 16)) * 0xd36d884b;
900         z = (z ^ (z >>> 16)) * 0xd36d884b;
901         return z ^ (z >>> 16);
902     }
903 
904     // Non-public (package only) support for spliterators needed by AbstractSplittableGenerator
905     // and AbstractArbitrarilyJumpableGenerator and AbstractSharedGenerator
906 
907     /**
908      * Base class for making Spliterator classes for streams of randomly chosen
909      * values.
910      */
911     public abstract static class RandomSpliterator {
912 
913         /** low range value */
914        public long index;
915 
916        /** high range value */
917        public final long fence;
918 
919        /** Constructor
920         *
921         * @param index  low range value
922         * @param fence  high range value
923         */
RandomSpliterator(long index, long fence)924         public RandomSpliterator(long index, long fence) {
925             this.index = index; this.fence = fence;
926         }
927 
928         /**
929          * Returns estimated size.
930          *
931          * @return estimated size
932          */
estimateSize()933         public long estimateSize() {
934             return fence - index;
935         }
936 
937         /**
938          * Returns characteristics.
939          *
940          * @return characteristics
941          */
characteristics()942         public int characteristics() {
943             return (Spliterator.SIZED | Spliterator.SUBSIZED |
944                     Spliterator.NONNULL | Spliterator.IMMUTABLE);
945         }
946     }
947 
948     /**
949      * Spliterators for int streams. These are based on abstract spliterator
950      * classes provided by class AbstractSpliteratorGenerator. Each one needs to
951      * define only a constructor and two methods.
952      */
953     public static class RandomIntsSpliterator extends RandomSupport.RandomSpliterator
954             implements Spliterator.OfInt {
955         final RandomGenerator generatingGenerator;
956         final int origin;
957         final int bound;
958 
959         /**
960          * RandomIntsSpliterator constructor.
961          *
962          * @param generatingGenerator base AbstractSpliteratorGenerator
963          * @param index the (inclusive) lower bound on traversal positions
964          * @param fence the (exclusive) upper bound on traversal positions
965          * @param origin the (inclusive) lower bound on the pseudorandom values to be generated
966          * @param bound the (exclusive) upper bound on the pseudorandom values to be generated
967          */
RandomIntsSpliterator(RandomGenerator generatingGenerator, long index, long fence, int origin, int bound)968         public RandomIntsSpliterator(RandomGenerator generatingGenerator,
969                                      long index, long fence, int origin, int bound) {
970             super(index, fence);
971             this.generatingGenerator = generatingGenerator;
972             this.origin = origin; this.bound = bound;
973         }
974 
trySplit()975         public Spliterator.OfInt trySplit() {
976             long i = index, m = (i + fence) >>> 1;
977             if (m <= i) return null;
978             index = m;
979             // The same generatingGenerator is used, with no splitting or copying.
980             return new RandomIntsSpliterator(generatingGenerator, i, m, origin, bound);
981         }
982 
tryAdvance(IntConsumer consumer)983         public boolean tryAdvance(IntConsumer consumer) {
984             Objects.requireNonNull(consumer);
985             long i = index, f = fence;
986             if (i < f) {
987                 consumer.accept(RandomSupport.boundedNextInt(generatingGenerator, origin, bound));
988                 index = i + 1;
989                 return true;
990             }
991             else return false;
992         }
993 
forEachRemaining(IntConsumer consumer)994         public void forEachRemaining(IntConsumer consumer) {
995             Objects.requireNonNull(consumer);
996             long i = index, f = fence;
997             if (i < f) {
998                 index = f;
999                 RandomGenerator r = generatingGenerator;
1000                 int o = origin, b = bound;
1001                 do {
1002                     consumer.accept(RandomSupport.boundedNextInt(r, o, b));
1003                 } while (++i < f);
1004             }
1005         }
1006     }
1007 
1008     /**
1009      * Spliterator for long streams.
1010      */
1011     public static class RandomLongsSpliterator extends RandomSupport.RandomSpliterator
1012             implements Spliterator.OfLong {
1013         final RandomGenerator generatingGenerator;
1014         final long origin;
1015         final long bound;
1016 
1017         /**
1018          * RandomLongsSpliterator constructor.
1019          *
1020          * @param generatingGenerator base AbstractSpliteratorGenerator
1021          * @param index the (inclusive) lower bound on traversal positions
1022          * @param fence the (exclusive) upper bound on traversal positions
1023          * @param origin the (inclusive) lower bound on the pseudorandom values to be generated
1024          * @param bound the (exclusive) upper bound on the pseudorandom values to be generated
1025          */
RandomLongsSpliterator(RandomGenerator generatingGenerator, long index, long fence, long origin, long bound)1026         public RandomLongsSpliterator(RandomGenerator generatingGenerator,
1027                                       long index, long fence, long origin, long bound) {
1028             super(index, fence);
1029             this.generatingGenerator = generatingGenerator;
1030             this.origin = origin; this.bound = bound;
1031         }
1032 
trySplit()1033         public Spliterator.OfLong trySplit() {
1034             long i = index, m = (i + fence) >>> 1;
1035             if (m <= i) return null;
1036             index = m;
1037             // The same generatingGenerator is used, with no splitting or copying.
1038             return new RandomLongsSpliterator(generatingGenerator, i, m, origin, bound);
1039         }
1040 
tryAdvance(LongConsumer consumer)1041         public boolean tryAdvance(LongConsumer consumer) {
1042             Objects.requireNonNull(consumer);
1043             long i = index, f = fence;
1044             if (i < f) {
1045                 consumer.accept(RandomSupport.boundedNextLong(generatingGenerator, origin, bound));
1046                 index = i + 1;
1047                 return true;
1048             }
1049             else return false;
1050         }
1051 
forEachRemaining(LongConsumer consumer)1052         public void forEachRemaining(LongConsumer consumer) {
1053             Objects.requireNonNull(consumer);
1054             long i = index, f = fence;
1055             if (i < f) {
1056                 index = f;
1057                 RandomGenerator r = generatingGenerator;
1058                 long o = origin, b = bound;
1059                 do {
1060                     consumer.accept(RandomSupport.boundedNextLong(r, o, b));
1061                 } while (++i < f);
1062             }
1063         }
1064     }
1065 
1066     /**
1067      * Spliterator for double streams.
1068      */
1069     public static class RandomDoublesSpliterator extends RandomSupport.RandomSpliterator
1070             implements Spliterator.OfDouble {
1071         final RandomGenerator generatingGenerator;
1072         final double origin;
1073         final double bound;
1074 
1075         /**
1076          * RandomDoublesSpliterator constructor.
1077          *
1078          * @param generatingGenerator base AbstractSpliteratorGenerator
1079          * @param index the (inclusive) lower bound on traversal positions
1080          * @param fence the (exclusive) upper bound on traversal positions
1081          * @param origin the (inclusive) lower bound on the pseudorandom values to be generated
1082          * @param bound the (exclusive) upper bound on the pseudorandom values to be generated
1083          */
RandomDoublesSpliterator(RandomGenerator generatingGenerator, long index, long fence, double origin, double bound)1084         public RandomDoublesSpliterator(RandomGenerator generatingGenerator,
1085                                         long index, long fence, double origin, double bound) {
1086             super(index, fence);
1087             this.generatingGenerator = generatingGenerator;
1088             this.origin = origin; this.bound = bound;
1089         }
1090 
trySplit()1091         public Spliterator.OfDouble trySplit() {
1092             long i = index, m = (i + fence) >>> 1;
1093             if (m <= i) return null;
1094             index = m;
1095             // The same generatingGenerator is used, with no splitting or copying.
1096             return new RandomDoublesSpliterator(generatingGenerator, i, m, origin, bound);
1097         }
1098 
tryAdvance(DoubleConsumer consumer)1099         public boolean tryAdvance(DoubleConsumer consumer) {
1100             Objects.requireNonNull(consumer);
1101             long i = index, f = fence;
1102             if (i < f) {
1103                 consumer.accept(RandomSupport.boundedNextDouble(generatingGenerator, origin, bound));
1104                 index = i + 1;
1105                 return true;
1106             }
1107             else return false;
1108         }
1109 
forEachRemaining(DoubleConsumer consumer)1110         public void forEachRemaining(DoubleConsumer consumer) {
1111             Objects.requireNonNull(consumer);
1112             long i = index, f = fence;
1113             if (i < f) {
1114                 index = f;
1115                 RandomGenerator r = generatingGenerator;
1116                 double o = origin, b = bound;
1117                 do {
1118                     consumer.accept(RandomSupport.boundedNextDouble(r, o, b));
1119                 } while (++i < f);
1120             }
1121         }
1122     }
1123 
1124     /**
1125      * Implementation support for the {@code nextExponential} method of
1126      * {@link java.util.random.RandomGenerator}.
1127      *
1128      * Certain details of the algorithm used in this method may depend critically
1129      * on the quality of the low-order bits delivered by {@code nextLong()}.  This method
1130      * should not be used with RNG algorithms (such as a simple Linear Congruential
1131      * Generator) whose low-order output bits do not have good statistical quality.
1132      *
1133      * @implNote The reference implementation uses McFarland's fast modified
1134      * ziggurat algorithm (largely table-driven, with rare cases handled by
1135      * computation and rejection sampling). Walker's alias method for sampling
1136      * a discrete distribution also plays a role.
1137      *
1138      * @param rng an instance of {@code RandomGenerator}, used to generate uniformly
1139      *            pseudorandomly chosen {@code long} values
1140      *
1141      * @return a nonnegative {@code double} value chosen pseudorandomly
1142      *         from an exponential distribution whose mean is 1
1143      */
computeNextExponential(RandomGenerator rng)1144     public static double computeNextExponential(RandomGenerator rng) {
1145         /*
1146          * The tables themselves, as well as a number of associated parameters, are
1147          * defined in class DoubleZigguratTables, which is automatically
1148          * generated by the program create_ziggurat_tables.c (which takes only a
1149          * few seconds to run).
1150          *
1151          * For more information about the algorithm, see these articles:
1152          *
1153          * Christopher D. McFarland.  2016 (published online 24 Jun 2015).  A modified ziggurat
1154          * algorithm for generating exponentially and normally distributed pseudorandom numbers.
1155          * Journal of Statistical Computation and Simulation 86 (7), pages 1281-1294.
1156          * https://www.tandfonline.com/doi/abs/10.1080/00949655.2015.1060234
1157          * Also at https://arxiv.org/abs/1403.6870 (26 March 2014).
1158          *
1159          * Alastair J. Walker.  1977.  An efficient method for generating discrete random
1160          * variables with general distributions. ACM Trans. Math. Software 3, 3
1161          * (September 1977), 253-256. DOI: https://doi.org/10.1145/355744.355749
1162          *
1163          */
1164         long U1 = rng.nextLong();
1165         // Experimentation on a variety of machines indicates that it is overall much faster
1166         // to do the following & and < operations on longs rather than first cast U1 to int
1167         // (but then we need to cast to int before doing the array indexing operation).
1168         long i = U1 & DoubleZigguratTables.exponentialLayerMask;
1169         if (i < DoubleZigguratTables.exponentialNumberOfLayers) {
1170             // This is the fast path (occurring more than 98% of the time).  Make an early exit.
1171             return DoubleZigguratTables.exponentialX[(int)i] * (U1 >>> 1);
1172         }
1173         // We didn't use the upper part of U1 after all.  We'll be able to use it later.
1174 
1175         for (double extra = 0.0; ; ) {
1176             // Use Walker's alias method to sample an (unsigned) integer j from a discrete
1177             // probability distribution that includes the tail and all the ziggurat overhangs;
1178             // j will be less than DoubleZigguratTables.exponentialNumberOfLayers + 1.
1179             long UA = rng.nextLong();
1180             int j = (int)UA & DoubleZigguratTables.exponentialAliasMask;
1181             if (UA >= DoubleZigguratTables.exponentialAliasThreshold[j]) {
1182                 j = DoubleZigguratTables.exponentialAliasMap[j] &
1183                         DoubleZigguratTables.exponentialSignCorrectionMask;
1184             }
1185             if (j > 0) {   // Sample overhang j
1186                 // For the exponential distribution, every overhang is convex.
1187                 final double[] X = DoubleZigguratTables.exponentialX;
1188                 final double[] Y = DoubleZigguratTables.exponentialY;
1189                 // At this point, the high-order bits of U1 have not been used yet,
1190                 // but we need the value in U1 to be positive.
1191                 for (U1 = (U1 >>> 1);; U1 = (rng.nextLong() >>> 1)) {
1192                     long U2 = (rng.nextLong() >>> 1);
1193                     // Does the point lie below the curve?
1194                     long Udiff = U2 - U1;
1195                     if (Udiff < 0) {
1196                         // We picked a point in the upper-right triangle.  None of those can be
1197                         // accepted.  So remap the point into the lower-left triangle and try that.
1198                         // In effect, we swap U1 and U2, and invert the sign of Udiff.
1199                         Udiff = -Udiff;
1200                         U2 = U1;
1201                         U1 -= Udiff;
1202                     }
1203                     // Compute the actual x-coordinate of the randomly chosen point.
1204                     double x = (X[j] * 0x1.0p63) + ((X[j-1] - X[j]) * (double)U1);
1205                     if (Udiff >= DoubleZigguratTables.exponentialConvexMargin) {
1206                         return x + extra;   // The chosen point is way below the curve; accept it.
1207                     }
1208                     // Compute the actual y-coordinate of the randomly chosen point.
1209                     double y = (Y[j] * 0x1.0p63) + ((Y[j-1] - Y[j]) * (double)U2);
1210                     // Now see how that y-coordinate compares to the curve
1211                     if (y <= Math.exp(-x)) {
1212                         return x + extra;   // The chosen point is below the curve; accept it.
1213                     }
1214                     // Otherwise, we reject this sample and have to try again.
1215                 }
1216             }
1217             // We are now committed to sampling from the tail.  We could do a recursive call
1218             // and then add X[0], but we save some time and stack space by using an iterative loop.
1219             extra += DoubleZigguratTables.exponentialX0;
1220             // This is like the first five lines of this method, but if it returns, it first adds "extra".
1221             U1 = rng.nextLong();
1222             i = U1 & DoubleZigguratTables.exponentialLayerMask;
1223             if (i < DoubleZigguratTables.exponentialNumberOfLayers) {
1224                 return DoubleZigguratTables.exponentialX[(int)i] * (U1 >>> 1) + extra;
1225             }
1226         }
1227     }
1228 
1229     /**
1230      * Implementation support for the {@code nextGaussian} methods of
1231      * {@link java.util.random.RandomGenerator}.
1232      *
1233      * Certain details of the algorithm used in this method may depend critically
1234      * on the quality of the low-order bits delivered by {@code nextLong()}.  This method
1235      * should not be used with RNG algorithms (such as a simple Linear Congruential
1236      * Generator) whose low-order output bits do not have good statistical quality.
1237      *
1238      * @implNote The reference implementation uses McFarland's fast modified
1239      * ziggurat algorithm (largely table-driven, with rare cases handled by
1240      * computation and rejection sampling). Walker's alias method for sampling
1241      * a discrete distribution also plays a role.
1242      *
1243      * @param rng an instance of {@code RandomGenerator}, used to generate uniformly
1244      *            pseudorandomly chosen {@code long} values
1245      *
1246      * @return a nonnegative {@code double} value chosen pseudorandomly
1247      *         from a Gaussian (normal) distribution whose mean is 0 and whose
1248      *         standard deviation is 1.
1249      */
computeNextGaussian(RandomGenerator rng)1250     public static double computeNextGaussian(RandomGenerator rng) {
1251         /*
1252          * The tables themselves, as well as a number of associated parameters, are
1253          * defined in class java.util.DoubleZigguratTables, which is automatically
1254          * generated by the program create_ziggurat_tables.c (which takes only a
1255          * few seconds to run).
1256          *
1257          * For more information about the algorithm, see these articles:
1258          *
1259          * Christopher D. McFarland.  2016 (published online 24 Jun 2015).  A modified ziggurat
1260          * algorithm for generating exponentially and normally distributed pseudorandom numbers.
1261          * Journal of Statistical Computation and Simulation 86 (7), pages 1281-1294.
1262          * https://www.tandfonline.com/doi/abs/10.1080/00949655.2015.1060234
1263          * Also at https://arxiv.org/abs/1403.6870 (26 March 2014).
1264          *
1265          * Alastair J. Walker.  1977.  An efficient method for generating discrete random
1266          * variables with general distributions. ACM Trans. Math. Software 3, 3
1267          * (September 1977), 253-256. DOI: https://doi.org/10.1145/355744.355749
1268          *
1269          */
1270         long U1 = rng.nextLong();
1271         // Experimentation on a variety of machines indicates that it is overall much faster
1272         // to do the following & and < operations on longs rather than first cast U1 to int
1273         // (but then we need to cast to int before doing the array indexing operation).
1274         long i = U1 & DoubleZigguratTables.normalLayerMask;
1275 
1276         if (i < DoubleZigguratTables.normalNumberOfLayers) {
1277             // This is the fast path (occurring more than 98% of the time).  Make an early exit.
1278             return DoubleZigguratTables.normalX[(int)i] * U1;   // Note that the sign bit of U1 is used here.
1279         }
1280         // We didn't use the upper part of U1 after all.
1281         // Pull U1 apart into a sign bit and a 63-bit value for later use.
1282         double signBit = (U1 >= 0) ? 1.0 : -1.0;
1283         U1 = (U1 << 1) >>> 1;
1284 
1285         // Use Walker's alias method to sample an (unsigned) integer j from a discrete
1286         // probability distribution that includes the tail and all the ziggurat overhangs;
1287         // j will be less than DoubleZigguratTables.normalNumberOfLayers + 1.
1288         long UA = rng.nextLong();
1289         int j = (int)UA & DoubleZigguratTables.normalAliasMask;
1290         if (UA >= DoubleZigguratTables.normalAliasThreshold[j]) {
1291             j = DoubleZigguratTables.normalAliasMap[j] & DoubleZigguratTables.normalSignCorrectionMask;
1292         }
1293 
1294         double x;
1295         // Now the goal is to choose the result, which will be multiplied by signBit just before return.
1296 
1297         // There are four kinds of overhangs:
1298         //
1299         //  j == 0                          :  Sample from tail
1300         //  0 < j < normalInflectionIndex   :  Overhang is convex; can reject upper-right triangle
1301         //  j == normalInflectionIndex      :  Overhang includes the inflection point
1302         //  j > normalInflectionIndex       :  Overhang is concave; can accept point in lower-left triangle
1303         //
1304         // Choose one of four loops to compute x, each specialized for a specific kind of overhang.
1305         // Conditional statements are arranged such that the more likely outcomes are first.
1306 
1307         // In the three cases other than the tail case:
1308         // U1 represents a fraction (scaled by 2**63) of the width of rectangle measured from the left.
1309         // U2 represents a fraction (scaled by 2**63) of the height of rectangle measured from the top.
1310         // Together they indicate a randomly chosen point within the rectangle.
1311 
1312         final double[] X = DoubleZigguratTables.normalX;
1313         final double[] Y = DoubleZigguratTables.normalY;
1314         if (j > DoubleZigguratTables.normalInflectionIndex) {   // Concave overhang
1315             for (;; U1 = (rng.nextLong() >>> 1)) {
1316                 long U2 = (rng.nextLong() >>> 1);
1317                 // Compute the actual x-coordinate of the randomly chosen point.
1318                 x = (X[j] * 0x1.0p63) + ((X[j-1] - X[j]) * (double)U1);
1319                 // Does the point lie below the curve?
1320                 long Udiff = U2 - U1;
1321                 if (Udiff >= 0) {
1322                     break;   // The chosen point is in the lower-left triangle; accept it.
1323                 }
1324                 if (Udiff <= -DoubleZigguratTables.normalConcaveMargin) {
1325                     continue;   // The chosen point is way above the curve; reject it.
1326                 }
1327                 // Compute the actual y-coordinate of the randomly chosen point.
1328                 double y = (Y[j] * 0x1.0p63) + ((Y[j-1] - Y[j]) * (double)U2);
1329                 // Now see how that y-coordinate compares to the curve
1330                 if (y <= Math.exp(-0.5*x*x)) {
1331                     break;   // The chosen point is below the curve; accept it.
1332                 }
1333                 // Otherwise, we reject this sample and have to try again.
1334             }
1335         } else if (j == 0) {   // Tail
1336             // Tail-sampling method of Marsaglia and Tsang.  See any one of:
1337             // Marsaglia and Tsang. 1984. A fast, easily implemented method for sampling from decreasing
1338             //    or symmetric unimodal density functions. SIAM J. Sci. Stat. Comput. 5, 349-359.
1339             // Marsaglia and Tsang. 1998. The Monty Python method for generating random variables.
1340             //    ACM Trans. Math. Softw. 24, 3 (September 1998), 341-350.  See page 342, step (4).
1341             //    http://doi.org/10.1145/292395.292453
1342             // Thomas, Luk, Leong, and Villasenor. 2007. Gaussian random number generators.
1343             //    ACM Comput. Surv. 39, 4, Article 11 (November 2007).  See Algorithm 16.
1344             //    http://doi.org/10.1145/1287620.1287622
1345             // Compute two separate random exponential samples and then compare them in certain way.
1346             do {
1347                 x = (1.0 / DoubleZigguratTables.normalX0) * computeNextExponential(rng);
1348             } while (computeNextExponential(rng) < 0.5*x*x);
1349             x += DoubleZigguratTables.normalX0;
1350         } else if (j < DoubleZigguratTables.normalInflectionIndex) {   // Convex overhang
1351             for (;; U1 = (rng.nextLong() >>> 1)) {
1352                 long U2 = (rng.nextLong() >>> 1);
1353                 // Does the point lie below the curve?
1354                 long Udiff = U2 - U1;
1355                 if (Udiff < 0) {
1356                     // We picked a point in the upper-right triangle.  None of those can be accepted.
1357                     // So remap the point into the lower-left triangle and try that.
1358                     // In effect, we swap U1 and U2, and invert the sign of Udiff.
1359                     Udiff = -Udiff;
1360                     U2 = U1;
1361                     U1 -= Udiff;
1362                 }
1363                 // Compute the actual x-coordinate of the randomly chosen point.
1364                 x = (X[j] * 0x1.0p63) + ((X[j-1] - X[j]) * (double)U1);
1365                 if (Udiff >= DoubleZigguratTables.normalConvexMargin) {
1366                     break;   // The chosen point is way below the curve; accept it.
1367                 }
1368                 // Compute the actual y-coordinate of the randomly chosen point.
1369                 double y = (Y[j] * 0x1.0p63) + ((Y[j-1] - Y[j]) * (double)U2);
1370                 // Now see how that y-coordinate compares to the curve
1371                 if (y <= Math.exp(-0.5*x*x)) break; // The chosen point is below the curve; accept it.
1372                 // Otherwise, we reject this sample and have to try again.
1373             }
1374         } else {
1375             // The overhang includes the inflection point, so the curve is both convex and concave
1376             for (;; U1 = (rng.nextLong() >>> 1)) {
1377                 long U2 = (rng.nextLong() >>> 1);
1378                 // Compute the actual x-coordinate of the randomly chosen point.
1379                 x = (X[j] * 0x1.0p63) + ((X[j-1] - X[j]) * (double)U1);
1380                 // Does the point lie below the curve?
1381                 long Udiff = U2 - U1;
1382                 if (Udiff >= DoubleZigguratTables.normalConvexMargin) {
1383                     break;   // The chosen point is way below the curve; accept it.
1384                 }
1385                 if (Udiff <= -DoubleZigguratTables.normalConcaveMargin) {
1386                     continue;   // The chosen point is way above the curve; reject it.
1387                 }
1388                 // Compute the actual y-coordinate of the randomly chosen point.
1389                 double y = (Y[j] * 0x1.0p63) + ((Y[j-1] - Y[j]) * (double)U2);
1390                 // Now see how that y-coordinate compares to the curve
1391                 if (y <= Math.exp(-0.5*x*x)) {
1392                     break;   // The chosen point is below the curve; accept it.
1393                 }
1394                 // Otherwise, we reject this sample and have to try again.
1395             }
1396         }
1397         return signBit*x;
1398     }
1399 
1400     /**
1401      * This class overrides the stream-producing methods (such as
1402      * {@link RandomGenerator#ints() ints}()) in class {@link RandomGenerator}
1403      * to provide {@link Spliterator}-based implmentations that support
1404      * potentially parallel execution.
1405      *
1406      * <p> To implement a pseudorandom number generator, the programmer needs
1407      * only to extend this class and provide implementations for the methods
1408      * {@link RandomGenerator#nextInt() nextInt}(),
1409      * {@link RandomGenerator#nextLong() nextLong}(),
1410      *
1411      * <p> This class is not public; it provides shared code to the public
1412      * classes {@link AbstractSplittableGenerator}, and
1413      * {@link AbstractArbitrarilyJumpableGenerator}.
1414      *
1415      * @since 17
1416      */
1417     public abstract static class AbstractSpliteratorGenerator implements RandomGenerator {
1418         /*
1419          * Implementation Overview.
1420          *
1421          * This class provides most of the "user API" methods needed to
1422          * satisfy the interface RandomGenerator.  An implementation of this
1423          * interface need only extend this class and provide implementations
1424          * of six methods: nextInt, nextLong, and nextDouble (the versions
1425          * that take no arguments).
1426          *
1427          * File organization: First the non-public abstract methods needed
1428          * to create spliterators, then the main public methods.
1429          */
1430 
1431         // stream methods, coded in a way intended to better isolate for
1432         // maintenance purposes the small differences across forms.
1433 
intStream(Spliterator.OfInt srng)1434         private static IntStream intStream(Spliterator.OfInt srng) {
1435             return StreamSupport.intStream(srng, false);
1436         }
1437 
longStream(Spliterator.OfLong srng)1438         private static LongStream longStream(Spliterator.OfLong srng) {
1439             return StreamSupport.longStream(srng, false);
1440         }
1441 
doubleStream(Spliterator.OfDouble srng)1442         private static DoubleStream doubleStream(Spliterator.OfDouble srng) {
1443             return StreamSupport.doubleStream(srng, false);
1444         }
1445 
1446         /* ---------------- public static methods ---------------- */
1447 
ints(RandomGenerator gen, long streamSize)1448        public static IntStream ints(RandomGenerator gen, long streamSize) {
1449             RandomSupport.checkStreamSize(streamSize);
1450             return intStream(new RandomIntsSpliterator(gen, 0L, streamSize, Integer.MAX_VALUE, 0));
1451         }
1452 
ints(RandomGenerator gen)1453         public static IntStream ints(RandomGenerator gen) {
1454             return intStream(new RandomIntsSpliterator(gen, 0L, Long.MAX_VALUE, Integer.MAX_VALUE, 0));
1455         }
1456 
ints(RandomGenerator gen, long streamSize, int randomNumberOrigin, int randomNumberBound)1457         public static IntStream ints(RandomGenerator gen, long streamSize, int randomNumberOrigin, int randomNumberBound) {
1458             RandomSupport.checkStreamSize(streamSize);
1459             RandomSupport.checkRange(randomNumberOrigin, randomNumberBound);
1460             return intStream(new RandomIntsSpliterator(gen, 0L, streamSize, randomNumberOrigin, randomNumberBound));
1461         }
1462 
ints(RandomGenerator gen, int randomNumberOrigin, int randomNumberBound)1463         public static IntStream ints(RandomGenerator gen, int randomNumberOrigin, int randomNumberBound) {
1464             RandomSupport.checkRange(randomNumberOrigin, randomNumberBound);
1465             return intStream(new RandomIntsSpliterator(gen, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound));
1466         }
1467 
longs(RandomGenerator gen, long streamSize)1468         public static LongStream longs(RandomGenerator gen, long streamSize) {
1469             RandomSupport.checkStreamSize(streamSize);
1470             return longStream(new RandomLongsSpliterator(gen, 0L, streamSize, Long.MAX_VALUE, 0L));
1471         }
1472 
longs(RandomGenerator gen)1473         public static LongStream longs(RandomGenerator gen) {
1474             return longStream(new RandomLongsSpliterator(gen, 0L, Long.MAX_VALUE, Long.MAX_VALUE, 0L));
1475         }
1476 
longs(RandomGenerator gen, long streamSize, long randomNumberOrigin, long randomNumberBound)1477         public static LongStream longs(RandomGenerator gen, long streamSize, long randomNumberOrigin, long randomNumberBound) {
1478             RandomSupport.checkStreamSize(streamSize);
1479             RandomSupport.checkRange(randomNumberOrigin, randomNumberBound);
1480             return longStream(new RandomLongsSpliterator(gen, 0L, streamSize, randomNumberOrigin, randomNumberBound));
1481         }
1482 
longs(RandomGenerator gen, long randomNumberOrigin, long randomNumberBound)1483         public static LongStream longs(RandomGenerator gen, long randomNumberOrigin, long randomNumberBound) {
1484             RandomSupport.checkRange(randomNumberOrigin, randomNumberBound);
1485             return longStream(new RandomLongsSpliterator(gen, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound));
1486         }
1487 
doubles(RandomGenerator gen, long streamSize)1488         public static DoubleStream doubles(RandomGenerator gen, long streamSize) {
1489             RandomSupport.checkStreamSize(streamSize);
1490             return doubleStream(new RandomDoublesSpliterator(gen, 0L, streamSize, Double.MAX_VALUE, 0.0));
1491         }
1492 
doubles(RandomGenerator gen)1493         public static DoubleStream doubles(RandomGenerator gen) {
1494             return doubleStream(new RandomDoublesSpliterator(gen, 0L, Long.MAX_VALUE, Double.MAX_VALUE, 0.0));
1495         }
1496 
doubles(RandomGenerator gen, long streamSize, double randomNumberOrigin, double randomNumberBound)1497         public static DoubleStream doubles(RandomGenerator gen, long streamSize, double randomNumberOrigin, double randomNumberBound) {
1498             RandomSupport.checkStreamSize(streamSize);
1499             RandomSupport.checkRange(randomNumberOrigin, randomNumberBound);
1500             return doubleStream(new RandomDoublesSpliterator(gen, 0L, streamSize, randomNumberOrigin, randomNumberBound));
1501         }
1502 
doubles(RandomGenerator gen, double randomNumberOrigin, double randomNumberBound)1503         public static DoubleStream doubles(RandomGenerator gen, double randomNumberOrigin, double randomNumberBound) {
1504             RandomSupport.checkRange(randomNumberOrigin, randomNumberBound);
1505             return doubleStream(new RandomDoublesSpliterator(gen, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound));
1506         }
1507 
1508         /* ---------------- public instance methods ---------------- */
1509 
ints(long streamSize)1510         public IntStream ints(long streamSize) {
1511             return ints(this, streamSize);
1512         }
1513 
ints()1514         public IntStream ints() {
1515             return ints(this);
1516         }
1517 
ints(long streamSize, int randomNumberOrigin, int randomNumberBound)1518         public IntStream ints(long streamSize, int randomNumberOrigin, int randomNumberBound) {
1519             return ints(this, streamSize, randomNumberOrigin, randomNumberBound);
1520         }
1521 
ints(int randomNumberOrigin, int randomNumberBound)1522         public IntStream ints(int randomNumberOrigin, int randomNumberBound) {
1523             return ints(this, randomNumberOrigin, randomNumberBound);
1524         }
1525 
longs(long streamSize)1526         public LongStream longs(long streamSize) {
1527             return longs(this, streamSize);
1528         }
1529 
longs()1530         public LongStream longs() {
1531             return longs(this);
1532         }
1533 
longs(long streamSize, long randomNumberOrigin,long randomNumberBound)1534         public LongStream longs(long streamSize, long randomNumberOrigin,long randomNumberBound) {
1535             return longs(this, streamSize, randomNumberOrigin, randomNumberBound);
1536         }
1537 
longs(long randomNumberOrigin, long randomNumberBound)1538         public LongStream longs(long randomNumberOrigin, long randomNumberBound) {
1539             return longs(this, randomNumberOrigin, randomNumberBound);
1540         }
1541 
doubles(long streamSize)1542         public DoubleStream doubles(long streamSize) {
1543             return doubles(this, streamSize);
1544         }
1545 
doubles()1546         public DoubleStream doubles() {
1547             return doubles(this);
1548         }
1549 
doubles(long streamSize, double randomNumberOrigin, double randomNumberBound)1550         public DoubleStream doubles(long streamSize, double randomNumberOrigin, double randomNumberBound) {
1551             return doubles(this, streamSize, randomNumberOrigin, randomNumberBound);
1552         }
1553 
doubles(double randomNumberOrigin, double randomNumberBound)1554         public DoubleStream doubles(double randomNumberOrigin, double randomNumberBound) {
1555             return doubles(this, randomNumberOrigin, randomNumberBound);
1556         }
1557 
1558     }
1559 
1560     /**
1561      * This class provides much of the implementation of the
1562      * {@link ArbitrarilyJumpableGenerator} interface, to minimize the effort
1563      * required to implement that interface.
1564      *
1565      * <p> To implement a pseudorandom number generator, the programmer needs
1566      * only to extend this class and provide implementations for the methods
1567      * {@link RandomGenerator#nextInt() nextInt}(),
1568      * {@link RandomGenerator#nextLong() nextLong}(),
1569      * {@link ArbitrarilyJumpableGenerator#copy() copy}(),
1570      * {@link JumpableGenerator#jumps(long) jumps}(long),
1571      * {@link ArbitrarilyJumpableGenerator#jumpPowerOfTwo(int) jumpPowerOfTwo}(logDistance),
1572      * {@link JumpableGenerator#jumpDistance() jumpDistance}(),
1573      * and
1574      * {@link LeapableGenerator#leapDistance() leapDistance}().
1575      *
1576      * <p> (If the pseudorandom number generator also has the ability to
1577      * split, then the programmer may wish to consider instead extending
1578      * {@link AbstractSplittableGenerator}.)
1579      *
1580      * <p> The programmer should generally provide at least three constructors:
1581      * one that takes no arguments, one that accepts a {@code long} seed value,
1582      * and one that accepts an array of seed {@code byte} values. This class
1583      * provides a public {@link RandomSupport#initialSeed() initialSeed}()
1584      * method that may be useful in initializing some static state from which to
1585      * derive defaults seeds for use by the no-argument constructor.
1586      *
1587      * <p> For the stream methods (such as {@link RandomGenerator#ints() ints}()
1588      * and {@link SplittableGenerator#splits() splits}()), this class provides
1589      * {@link Spliterator}-based implementations that allow parallel execution
1590      * when appropriate. In this respect {@link ArbitrarilyJumpableGenerator}
1591      * differs from {@link JumpableGenerator}, which provides very simple
1592      * implementations that produce sequential streams only.
1593      *
1594      * <p> An implementation of the {@link AbstractArbitrarilyJumpableGenerator}
1595      * class must provide concrete definitions for the methods
1596      * {@link RandomGenerator#nextInt() nextInt}(),
1597      * {@link RandomGenerator#nextLong() nextLong}(),
1598      * {@link AbstractArbitrarilyJumpableGenerator#jumps(double) jumps}(double),
1599      * {@link JumpableGenerator#jumpDistance() jumpDistance}(),
1600      * and
1601      * {@link LeapableGenerator#leapDistance() leapDistance}().
1602      * Default implementations are provided for all other methods.
1603      *
1604      * <p> The documentation for each non-abstract method in this class
1605      * describes its implementation in detail. Each of these methods may be
1606      * overridden if the pseudorandom number generator being implemented
1607      * admits a more efficient implementation.
1608      *
1609      * @since 17
1610      */
1611     public abstract static class AbstractArbitrarilyJumpableGenerator
1612             extends AbstractSpliteratorGenerator implements RandomGenerator.ArbitrarilyJumpableGenerator {
1613 
1614         /*
1615          * Implementation Overview.
1616          *
1617          * This class provides most of the "user API" methods needed to satisfy
1618          * the interface ArbitrarilyJumpableGenerator.  Most of these methods
1619          * are in turn inherited from AbstractGenerator and the non-public class
1620          * AbstractSpliteratorGenerator; this file implements four versions of the
1621          * jumps method and defines the spliterators necessary to support them.
1622          *
1623          * File organization: First the non-public methods needed by the class
1624          * AbstractSpliteratorGenerator, then the main public methods, followed by some
1625          * custom spliterator classes needed for stream methods.
1626          */
1627 
1628         /**
1629          * Explicit constructor.
1630          */
AbstractArbitrarilyJumpableGenerator()1631         protected AbstractArbitrarilyJumpableGenerator() {
1632         }
1633 
1634         // Similar methods used by this class
1635 
makeJumpsSpliterator(long index, long fence, double distance)1636         Spliterator<RandomGenerator> makeJumpsSpliterator(long index, long fence, double distance) {
1637             return new RandomJumpsSpliterator(this, index, fence, distance);
1638         }
1639 
makeLeapsSpliterator(long index, long fence, double distance)1640         Spliterator<JumpableGenerator> makeLeapsSpliterator(long index, long fence, double distance) {
1641             return new RandomLeapsSpliterator(this, index, fence, distance);
1642         }
1643 
makeArbitraryJumpsSpliterator(long index, long fence, double distance)1644         Spliterator<ArbitrarilyJumpableGenerator> makeArbitraryJumpsSpliterator(long index, long fence, double distance) {
1645             return new RandomArbitraryJumpsSpliterator(this, index, fence, distance);
1646         }
1647 
1648         /* ---------------- public methods ---------------- */
1649 
1650         /**
1651          * Returns a new generator whose internal state is an exact copy of this
1652          * generator (therefore their future behavior should be identical if
1653          * subjected to the same series of operations).
1654          *
1655          * @return a new object that is a copy of this generator
1656          */
copy()1657         public abstract AbstractArbitrarilyJumpableGenerator copy();
1658 
1659         // Stream methods for jumping
1660 
stream(Spliterator<T> srng)1661         private static <T> Stream<T> stream(Spliterator<T> srng) {
1662             return StreamSupport.stream(srng, false);
1663         }
1664 
1665         @Override
jumps()1666         public Stream<RandomGenerator> jumps() {
1667             return stream(makeJumpsSpliterator(0L, Long.MAX_VALUE, jumpDistance()));
1668         }
1669 
1670         @Override
jumps(long streamSize)1671         public Stream<RandomGenerator> jumps(long streamSize) {
1672             RandomSupport.checkStreamSize(streamSize);
1673             return stream(makeJumpsSpliterator(0L, streamSize, jumpDistance()));
1674         }
1675 
1676         @Override
jumps(double distance)1677         public Stream<ArbitrarilyJumpableGenerator> jumps(double distance) {
1678             return stream(makeArbitraryJumpsSpliterator(0L, Long.MAX_VALUE, distance));
1679         }
1680 
1681         @Override
jumps(long streamSize, double distance)1682         public Stream<ArbitrarilyJumpableGenerator> jumps(long streamSize, double distance) {
1683             RandomSupport.checkStreamSize(streamSize);
1684             return stream(makeArbitraryJumpsSpliterator(0L, streamSize, distance));
1685         }
1686 
1687         @Override
leap()1688         public void leap() {
1689             jump(leapDistance());
1690         }
1691 
1692         // Stream methods for leaping
1693 
1694         @Override
leaps()1695         public Stream<JumpableGenerator> leaps() {
1696             return stream(makeLeapsSpliterator(0L, Long.MAX_VALUE, leapDistance()));
1697         }
1698 
1699         @Override
leaps(long streamSize)1700         public Stream<JumpableGenerator> leaps(long streamSize) {
1701             return stream(makeLeapsSpliterator(0L, streamSize, leapDistance()));
1702         }
1703 
1704 
1705         /**
1706          * Spliterator for int streams. We multiplex the four int versions into
1707          * one class by treating a bound less than origin as unbounded, and also
1708          * by treating "infinite" as equivalent to
1709          * {@link Long#MAX_VALUE Long.MAX_VALUE}. For splits, we choose to
1710          * override the method {@code trySplit()} to try to optimize execution
1711          * speed: instead of dividing a range in half, it breaks off the largest
1712          * possible chunk whose size is a power of two such that the remaining
1713          * chunk is not empty. In this way, the necessary jump distances will
1714          * tend to be powers of two. The long and double versions of this class
1715          * are identical except for types.
1716          */
1717         static class RandomIntsSpliterator extends RandomSupport.RandomSpliterator implements Spliterator.OfInt {
1718             final ArbitrarilyJumpableGenerator generatingGenerator;
1719             final int origin;
1720             final int bound;
1721 
RandomIntsSpliterator(ArbitrarilyJumpableGenerator generatingGenerator, long index, long fence, int origin, int bound)1722             RandomIntsSpliterator(ArbitrarilyJumpableGenerator generatingGenerator, long index, long fence, int origin, int bound) {
1723                 super(index, fence);
1724                 this.origin = origin; this.bound = bound;
1725                 this.generatingGenerator = generatingGenerator;
1726             }
1727 
trySplit()1728             public Spliterator.OfInt trySplit() {
1729                 long i = index, delta = Long.highestOneBit((fence - i) - 1), m = i + delta;
1730                 if (m <= i) return null;
1731                 index = m;
1732                 ArbitrarilyJumpableGenerator r = generatingGenerator;
1733                 return new RandomIntsSpliterator(r.copyAndJump((double)delta), i, m, origin, bound);
1734             }
1735 
tryAdvance(IntConsumer consumer)1736             public boolean tryAdvance(IntConsumer consumer) {
1737                 Objects.requireNonNull(consumer);
1738                 long i = index, f = fence;
1739                 if (i < f) {
1740                     consumer.accept(RandomSupport.boundedNextInt(generatingGenerator, origin, bound));
1741                     index = i + 1;
1742                     return true;
1743                 }
1744                 else return false;
1745             }
1746 
forEachRemaining(IntConsumer consumer)1747             public void forEachRemaining(IntConsumer consumer) {
1748                 Objects.requireNonNull(consumer);
1749                 long i = index, f = fence;
1750                 if (i < f) {
1751                     index = f;
1752                     ArbitrarilyJumpableGenerator r = generatingGenerator;
1753                     int o = origin, b = bound;
1754                     do {
1755                         consumer.accept(RandomSupport.boundedNextInt(r, o, b));
1756                     } while (++i < f);
1757                 }
1758             }
1759         }
1760 
1761         /**
1762          * Spliterator for long streams.
1763          */
1764         static class RandomLongsSpliterator extends RandomSupport.RandomSpliterator implements Spliterator.OfLong {
1765             final ArbitrarilyJumpableGenerator generatingGenerator;
1766             final long origin;
1767             final long bound;
1768 
RandomLongsSpliterator(ArbitrarilyJumpableGenerator generatingGenerator, long index, long fence, long origin, long bound)1769             RandomLongsSpliterator(ArbitrarilyJumpableGenerator generatingGenerator, long index, long fence, long origin, long bound) {
1770                 super(index, fence);
1771                 this.generatingGenerator = generatingGenerator;
1772                 this.origin = origin; this.bound = bound;
1773             }
1774 
trySplit()1775             public Spliterator.OfLong trySplit() {
1776                 long i = index, delta = Long.highestOneBit((fence - i) - 1), m = i + delta;
1777                 if (m <= i) return null;
1778                 index = m;
1779                 ArbitrarilyJumpableGenerator r = generatingGenerator;
1780                 return new RandomLongsSpliterator(r.copyAndJump((double)delta), i, m, origin, bound);
1781             }
1782 
tryAdvance(LongConsumer consumer)1783             public boolean tryAdvance(LongConsumer consumer) {
1784                 Objects.requireNonNull(consumer);
1785                 long i = index, f = fence;
1786                 if (i < f) {
1787                     consumer.accept(RandomSupport.boundedNextLong(generatingGenerator, origin, bound));
1788                     index = i + 1;
1789                     return true;
1790                 }
1791                 else return false;
1792             }
1793 
forEachRemaining(LongConsumer consumer)1794             public void forEachRemaining(LongConsumer consumer) {
1795                 Objects.requireNonNull(consumer);
1796                 long i = index, f = fence;
1797                 if (i < f) {
1798                     index = f;
1799                     ArbitrarilyJumpableGenerator r = generatingGenerator;
1800                     long o = origin, b = bound;
1801                     do {
1802                         consumer.accept(RandomSupport.boundedNextLong(r, o, b));
1803                     } while (++i < f);
1804                 }
1805             }
1806         }
1807 
1808         /**
1809          * Spliterator for double streams.
1810          */
1811         static class RandomDoublesSpliterator extends RandomSupport.RandomSpliterator implements Spliterator.OfDouble {
1812             final ArbitrarilyJumpableGenerator generatingGenerator;
1813             final double origin;
1814             final double bound;
1815 
RandomDoublesSpliterator(ArbitrarilyJumpableGenerator generatingGenerator, long index, long fence, double origin, double bound)1816             RandomDoublesSpliterator(ArbitrarilyJumpableGenerator generatingGenerator, long index, long fence, double origin, double bound) {
1817                 super(index, fence);
1818                 this.generatingGenerator = generatingGenerator;
1819                 this.origin = origin; this.bound = bound;
1820             }
1821 
trySplit()1822             public Spliterator.OfDouble trySplit() {
1823 
1824                 long i = index, delta = Long.highestOneBit((fence - i) - 1), m = i + delta;
1825                 if (m <= i) return null;
1826                 index = m;
1827                 ArbitrarilyJumpableGenerator r = generatingGenerator;
1828                 return new RandomDoublesSpliterator(r.copyAndJump((double)delta), i, m, origin, bound);
1829             }
1830 
tryAdvance(DoubleConsumer consumer)1831             public boolean tryAdvance(DoubleConsumer consumer) {
1832                 Objects.requireNonNull(consumer);
1833                 long i = index, f = fence;
1834                 if (i < f) {
1835                     consumer.accept(RandomSupport.boundedNextDouble(generatingGenerator, origin, bound));
1836                     index = i + 1;
1837                     return true;
1838                 }
1839                 else return false;
1840             }
1841 
forEachRemaining(DoubleConsumer consumer)1842             public void forEachRemaining(DoubleConsumer consumer) {
1843                 Objects.requireNonNull(consumer);
1844                 long i = index, f = fence;
1845                 if (i < f) {
1846                     index = f;
1847                     ArbitrarilyJumpableGenerator r = generatingGenerator;
1848                     double o = origin, b = bound;
1849                     do {
1850                         consumer.accept(RandomSupport.boundedNextDouble(r, o, b));
1851                     } while (++i < f);
1852                 }
1853             }
1854         }
1855 
1856         // Spliterators for producing new generators by jumping or leaping.  The
1857         // complete implementation of each of these spliterators is right here.
1858         // In the same manner as for the preceding spliterators, the method trySplit() is
1859         // coded to optimize execution speed: instead of dividing a range
1860         // in half, it breaks off the largest possible chunk whose
1861         // size is a power of two such that the remaining chunk is not
1862         // empty.  In this way, the necessary jump distances will tend to be
1863         // powers of two.
1864 
1865         /**
1866          * Spliterator for stream of generators of type RandomGenerator produced
1867          * by jumps.
1868          */
1869         static class RandomJumpsSpliterator extends RandomSupport.RandomSpliterator implements Spliterator<RandomGenerator> {
1870             ArbitrarilyJumpableGenerator generatingGenerator;
1871             final double distance;
1872 
RandomJumpsSpliterator(ArbitrarilyJumpableGenerator generatingGenerator, long index, long fence, double distance)1873             RandomJumpsSpliterator(ArbitrarilyJumpableGenerator generatingGenerator, long index, long fence, double distance) {
1874                 super(index, fence);
1875                 this.generatingGenerator = generatingGenerator; this.distance = distance;
1876             }
1877 
trySplit()1878             public Spliterator<RandomGenerator> trySplit() {
1879                 long i = index, delta = Long.highestOneBit((fence - i) - 1), m = i + delta;
1880                 if (m <= i) return null;
1881                 index = m;
1882                 ArbitrarilyJumpableGenerator r = generatingGenerator;
1883                 // Because delta is a power of two, (distance * (double)delta) can always be computed exactly.
1884                 return new RandomJumpsSpliterator(r.copyAndJump(distance * (double)delta), i, m, distance);
1885             }
1886 
tryAdvance(Consumer<? super RandomGenerator> consumer)1887             public boolean tryAdvance(Consumer<? super RandomGenerator> consumer) {
1888                 Objects.requireNonNull(consumer);
1889                 long i = index, f = fence;
1890                 if (i < f) {
1891                     consumer.accept(generatingGenerator.copyAndJump(distance));
1892                     index = i + 1;
1893                     return true;
1894                 }
1895                 return false;
1896             }
1897 
forEachRemaining(Consumer<? super RandomGenerator> consumer)1898             public void forEachRemaining(Consumer<? super RandomGenerator> consumer) {
1899                 Objects.requireNonNull(consumer);
1900                 long i = index, f = fence;
1901                 if (i < f) {
1902                     index = f;
1903                     ArbitrarilyJumpableGenerator r = generatingGenerator;
1904                     do {
1905                         consumer.accept(r.copyAndJump(distance));
1906                     } while (++i < f);
1907                 }
1908             }
1909         }
1910 
1911         /**
1912          * Spliterator for stream of generators of type RandomGenerator produced
1913          * by leaps.
1914          */
1915         static class RandomLeapsSpliterator extends RandomSupport.RandomSpliterator implements Spliterator<JumpableGenerator> {
1916             ArbitrarilyJumpableGenerator generatingGenerator;
1917             final double distance;
1918 
RandomLeapsSpliterator(ArbitrarilyJumpableGenerator generatingGenerator, long index, long fence, double distance)1919             RandomLeapsSpliterator(ArbitrarilyJumpableGenerator generatingGenerator, long index, long fence, double distance) {
1920                 super(index, fence);
1921                 this.generatingGenerator = generatingGenerator; this.distance = distance;
1922             }
1923 
trySplit()1924             public Spliterator<JumpableGenerator> trySplit() {
1925                 long i = index, delta = Long.highestOneBit((fence - i) - 1), m = i + delta;
1926                 if (m <= i) return null;
1927                 index = m;
1928                 // Because delta is a power of two, (distance * (double)delta) can always be computed exactly.
1929                 return new RandomLeapsSpliterator(generatingGenerator.copyAndJump(distance * (double)delta), i, m, distance);
1930             }
1931 
tryAdvance(Consumer<? super JumpableGenerator> consumer)1932             public boolean tryAdvance(Consumer<? super JumpableGenerator> consumer) {
1933                 Objects.requireNonNull(consumer);
1934                 long i = index, f = fence;
1935                 if (i < f) {
1936                     consumer.accept(generatingGenerator.copyAndJump(distance));
1937                     index = i + 1;
1938                     return true;
1939                 }
1940                 return false;
1941             }
1942 
forEachRemaining(Consumer<? super JumpableGenerator> consumer)1943             public void forEachRemaining(Consumer<? super JumpableGenerator> consumer) {
1944                 Objects.requireNonNull(consumer);
1945                 long i = index, f = fence;
1946                 if (i < f) {
1947                     index = f;
1948                     ArbitrarilyJumpableGenerator r = generatingGenerator;
1949                     do {
1950                         consumer.accept(r.copyAndJump(distance));
1951                     } while (++i < f);
1952                 }
1953             }
1954         }
1955 
1956         /**
1957          * Spliterator for stream of generators of type RandomGenerator produced
1958          * by arbitrary jumps.
1959          */
1960         static class RandomArbitraryJumpsSpliterator extends RandomSupport.RandomSpliterator implements Spliterator<ArbitrarilyJumpableGenerator> {
1961             ArbitrarilyJumpableGenerator generatingGenerator;
1962             final double distance;
1963 
RandomArbitraryJumpsSpliterator(ArbitrarilyJumpableGenerator generatingGenerator, long index, long fence, double distance)1964             RandomArbitraryJumpsSpliterator(ArbitrarilyJumpableGenerator generatingGenerator, long index, long fence, double distance) {
1965                 super(index, fence);
1966                 this.generatingGenerator = generatingGenerator; this.distance = distance;
1967             }
1968 
trySplit()1969             public Spliterator<ArbitrarilyJumpableGenerator> trySplit() {
1970                 long i = index, delta = Long.highestOneBit((fence - i) - 1), m = i + delta;
1971                 if (m <= i) return null;
1972                 index = m;
1973                 // Because delta is a power of two, (distance * (double)delta) can always be computed exactly.
1974                 return new RandomArbitraryJumpsSpliterator(generatingGenerator.copyAndJump(distance * (double)delta), i, m, distance);
1975             }
1976 
tryAdvance(Consumer<? super ArbitrarilyJumpableGenerator> consumer)1977             public boolean tryAdvance(Consumer<? super ArbitrarilyJumpableGenerator> consumer) {
1978                 Objects.requireNonNull(consumer);
1979                 long i = index, f = fence;
1980                 if (i < f) {
1981                     consumer.accept(generatingGenerator.copyAndJump(distance));
1982                     index = i + 1;
1983                     return true;
1984                 }
1985                 return false;
1986             }
1987 
forEachRemaining(Consumer<? super ArbitrarilyJumpableGenerator> consumer)1988             public void forEachRemaining(Consumer<? super ArbitrarilyJumpableGenerator> consumer) {
1989                 Objects.requireNonNull(consumer);
1990                 long i = index, f = fence;
1991                 if (i < f) {
1992                     index = f;
1993                     ArbitrarilyJumpableGenerator r = generatingGenerator;
1994                     do {
1995                         consumer.accept(r.copyAndJump(distance));
1996                     } while (++i < f);
1997                 }
1998             }
1999         }
2000 
2001     }
2002 
2003     /**
2004      * This class provides much of the implementation of the
2005      * {@link SplittableGenerator} interface, to minimize the effort required to
2006      * implement this interface.
2007      *
2008      * <p> To implement a pseudorandom number generator, the programmer needs
2009      * only to extend this class and provide implementations for the methods
2010      * {@link RandomGenerator#nextInt() nextInt}(),
2011      * {@link RandomGenerator#nextLong() nextLong}(),
2012      * {@link SplittableGenerator#split(SplittableGenerator) split}(splittable).
2013      *
2014      * <p> (If the pseudorandom number generator also has the ability to jump
2015      * an arbitrary specified distance, then the programmer may wish to consider
2016      * instead extending the class {@link AbstractArbitrarilyJumpableGenerator}.
2017      * See also the class {@link AbstractSplittableWithBrineGenerator}.)
2018      *
2019      * <p> The programmer should generally provide at least three constructors:
2020      * one that takes no arguments, one that accepts a {@code long} seed value,
2021      * and one that accepts an array of seed {@code byte} values. This class
2022      * provides a public {@link RandomSupport#initialSeed() initialSeed}()
2023      * method that may be useful in initializing some static state from which to
2024      * derive defaults seeds for use by the no-argument constructor.
2025      *
2026      * <p> For the stream methods (such as {@link RandomGenerator#ints() ints}()
2027      * and {@link SplittableGenerator#splits() splits}()), this class provides
2028      * {@link Spliterator}-based implementations that allow parallel execution
2029      * when appropriate.
2030      *
2031      * <p> The documentation for each non-abstract method in this class
2032      * describes its implementation in detail. Each of these methods may be
2033      * overridden if the pseudorandom number generator being implemented
2034      * admits a more efficient implementation.
2035      *
2036      * @since 17
2037      */
2038     public abstract static class AbstractSplittableGenerator extends AbstractSpliteratorGenerator implements SplittableGenerator {
2039 
2040         /*
2041          * Implementation Overview.
2042          *
2043          * This class provides most of the "user API" methods needed to
2044          * satisfy the interface SplittableGenerator.  Most of these methods
2045          * are in turn inherited from AbstractGenerator and the non-public class
2046          * AbstractSpliteratorGenerator; this class provides two versions of the
2047          * splits method and defines the spliterators necessary to support
2048          * them.
2049          *
2050          * File organization: First the non-public methods needed by the class
2051          * AbstractSpliteratorGenerator, then the main public methods, followed by some
2052          * custom spliterator classes.
2053          */
2054 
2055         /**
2056          * Explicit constructor.
2057          */
AbstractSplittableGenerator()2058         protected AbstractSplittableGenerator() {
2059         }
2060 
makeSplitsSpliterator(long index, long fence, SplittableGenerator source)2061         Spliterator<SplittableGenerator> makeSplitsSpliterator(long index, long fence, SplittableGenerator source) {
2062             return new RandomSplitsSpliterator(source, index, fence, this);
2063         }
2064 
2065         /* ---------------- public methods ---------------- */
2066 
2067         /**
2068          * Implements the @code{split()} method as
2069          * {@link SplittableGenerator#split(SplittableGenerator) split}(this).
2070          *
2071          * @return the new {@link SplittableGenerator} instance
2072          */
split()2073         public SplittableGenerator split() {
2074             return this.split(this);
2075         }
2076 
2077         // Stream methods for splittings
2078 
2079         @Override
splits()2080         public Stream<SplittableGenerator> splits() {
2081             return this.splits(Long.MAX_VALUE, this);
2082         }
2083 
2084         @Override
splits(long streamSize)2085         public Stream<SplittableGenerator> splits(long streamSize) {
2086             return this.splits(streamSize, this);
2087         }
2088 
2089         @Override
splits(SplittableGenerator source)2090         public Stream<SplittableGenerator> splits(SplittableGenerator source) {
2091             return this.splits(Long.MAX_VALUE, source);
2092         }
2093 
2094         @Override
splits(long streamSize, SplittableGenerator source)2095         public Stream<SplittableGenerator> splits(long streamSize, SplittableGenerator source) {
2096             RandomSupport.checkStreamSize(streamSize);
2097             Objects.requireNonNull(source, "source should be non-null");
2098 
2099             return StreamSupport.stream(makeSplitsSpliterator(0L, streamSize, source), false);
2100         }
2101 
2102         /**
2103          * Spliterator for int streams. We multiplex the four int versions into
2104          * one class by treating a bound less than origin as unbounded, and also
2105          * by treating "infinite" as equivalent to
2106          * {@link Long#MAX_VALUE Long.MAX_VALUE}. For splits, it uses the
2107          * standard divide-by-two approach. The long and double versions of this
2108          * class are identical except for types.
2109          */
2110         static class RandomIntsSpliterator extends RandomSupport.RandomSpliterator implements Spliterator.OfInt {
2111             final SplittableGenerator generatingGenerator;
2112             final int origin;
2113             final int bound;
2114 
RandomIntsSpliterator(SplittableGenerator generatingGenerator, long index, long fence, int origin, int bound)2115             RandomIntsSpliterator(SplittableGenerator generatingGenerator, long index, long fence, int origin, int bound) {
2116                 super(index, fence);
2117                 this.generatingGenerator = generatingGenerator;
2118                 this.origin = origin; this.bound = bound;
2119             }
2120 
trySplit()2121             public Spliterator.OfInt trySplit() {
2122                 long i = index, m = (i + fence) >>> 1;
2123                 if (m <= i) return null;
2124                 index = m;
2125                 return new RandomIntsSpliterator(generatingGenerator.split(), i, m, origin, bound);
2126             }
2127 
tryAdvance(IntConsumer consumer)2128             public boolean tryAdvance(IntConsumer consumer) {
2129                 Objects.requireNonNull(consumer);
2130                 long i = index, f = fence;
2131                 if (i < f) {
2132                     consumer.accept(RandomSupport.boundedNextInt(generatingGenerator, origin, bound));
2133                     index = i + 1;
2134                     return true;
2135                 }
2136                 else return false;
2137             }
2138 
forEachRemaining(IntConsumer consumer)2139             public void forEachRemaining(IntConsumer consumer) {
2140                 Objects.requireNonNull(consumer);
2141                 long i = index, f = fence;
2142                 if (i < f) {
2143                     index = f;
2144                     RandomGenerator r = generatingGenerator;
2145                     int o = origin, b = bound;
2146                     do {
2147                         consumer.accept(RandomSupport.boundedNextInt(r, o, b));
2148                     } while (++i < f);
2149                 }
2150             }
2151         }
2152 
2153         /**
2154          * Spliterator for long streams.
2155          */
2156         static class RandomLongsSpliterator extends RandomSupport.RandomSpliterator implements Spliterator.OfLong {
2157             final SplittableGenerator generatingGenerator;
2158             final long origin;
2159             final long bound;
2160 
RandomLongsSpliterator(SplittableGenerator generatingGenerator, long index, long fence, long origin, long bound)2161             RandomLongsSpliterator(SplittableGenerator generatingGenerator, long index, long fence, long origin, long bound) {
2162                 super(index, fence);
2163                 this.generatingGenerator = generatingGenerator;
2164                 this.origin = origin; this.bound = bound;
2165             }
2166 
trySplit()2167             public Spliterator.OfLong trySplit() {
2168                 long i = index, m = (i + fence) >>> 1;
2169                 if (m <= i) return null;
2170                 index = m;
2171                 return new RandomLongsSpliterator(generatingGenerator.split(), i, m, origin, bound);
2172             }
2173 
tryAdvance(LongConsumer consumer)2174             public boolean tryAdvance(LongConsumer consumer) {
2175                 Objects.requireNonNull(consumer);
2176                 long i = index, f = fence;
2177                 if (i < f) {
2178                     consumer.accept(RandomSupport.boundedNextLong(generatingGenerator, origin, bound));
2179                     index = i + 1;
2180                     return true;
2181                 }
2182                 else return false;
2183             }
2184 
forEachRemaining(LongConsumer consumer)2185             public void forEachRemaining(LongConsumer consumer) {
2186                 Objects.requireNonNull(consumer);
2187                 long i = index, f = fence;
2188                 if (i < f) {
2189                     index = f;
2190                     RandomGenerator r = generatingGenerator;
2191                     long o = origin, b = bound;
2192                     do {
2193                         consumer.accept(RandomSupport.boundedNextLong(r, o, b));
2194                     } while (++i < f);
2195                 }
2196             }
2197         }
2198 
2199         /**
2200          * Spliterator for double streams.
2201          */
2202         static class RandomDoublesSpliterator extends RandomSupport.RandomSpliterator implements Spliterator.OfDouble {
2203             final SplittableGenerator generatingGenerator;
2204             final double origin;
2205             final double bound;
2206 
RandomDoublesSpliterator(SplittableGenerator generatingGenerator, long index, long fence, double origin, double bound)2207             RandomDoublesSpliterator(SplittableGenerator generatingGenerator, long index, long fence, double origin, double bound) {
2208                 super(index, fence);
2209                 this.generatingGenerator = generatingGenerator;
2210                 this.origin = origin; this.bound = bound;
2211             }
2212 
trySplit()2213             public Spliterator.OfDouble trySplit() {
2214                 long i = index, m = (i + fence) >>> 1;
2215                 if (m <= i) return null;
2216                 index = m;
2217                 return new RandomDoublesSpliterator(generatingGenerator.split(), i, m, origin, bound);
2218             }
2219 
tryAdvance(DoubleConsumer consumer)2220             public boolean tryAdvance(DoubleConsumer consumer) {
2221                 Objects.requireNonNull(consumer);
2222                 long i = index, f = fence;
2223                 if (i < f) {
2224                     consumer.accept(RandomSupport.boundedNextDouble(generatingGenerator, origin, bound));
2225                     index = i + 1;
2226                     return true;
2227                 }
2228                 else return false;
2229             }
2230 
forEachRemaining(DoubleConsumer consumer)2231             public void forEachRemaining(DoubleConsumer consumer) {
2232                 Objects.requireNonNull(consumer);
2233                 long i = index, f = fence;
2234                 if (i < f) {
2235                     index = f;
2236                     RandomGenerator r = generatingGenerator;
2237                     double o = origin, b = bound;
2238                     do {
2239                         consumer.accept(RandomSupport.boundedNextDouble(r, o, b));
2240                     } while (++i < f);
2241                 }
2242             }
2243         }
2244 
2245         /**
2246          * Spliterator for stream of generators of type SplittableGenerator. We
2247          * multiplex the two versions into one class by treating "infinite" as
2248          * equivalent to Long.MAX_VALUE. For splits, it uses the standard
2249          * divide-by-two approach.
2250          */
2251         static class RandomSplitsSpliterator extends RandomSpliterator implements Spliterator<SplittableGenerator> {
2252             final SplittableGenerator generatingGenerator;
2253             final SplittableGenerator constructingGenerator;
2254 
RandomSplitsSpliterator(SplittableGenerator generatingGenerator, long index, long fence, SplittableGenerator constructingGenerator)2255             RandomSplitsSpliterator(SplittableGenerator generatingGenerator,
2256                                     long index, long fence,
2257                                     SplittableGenerator constructingGenerator) {
2258                 super(index, fence);
2259                 this.generatingGenerator = generatingGenerator;
2260                 this.constructingGenerator = constructingGenerator;
2261             }
2262 
trySplit()2263             public Spliterator<SplittableGenerator> trySplit() {
2264                 long i = index, m = (i + fence) >>> 1;
2265                 if (m <= i) return null;
2266                 index = m;
2267                 return new RandomSplitsSpliterator(generatingGenerator.split(), i, m, constructingGenerator);
2268             }
2269 
tryAdvance(Consumer<? super SplittableGenerator> consumer)2270             public boolean tryAdvance(Consumer<? super SplittableGenerator> consumer) {
2271                 Objects.requireNonNull(consumer);
2272                 long i = index, f = fence;
2273                 if (i < f) {
2274                     consumer.accept(constructingGenerator.split(generatingGenerator));
2275                     index = i + 1;
2276                     return true;
2277                 }
2278                 else return false;
2279             }
2280 
forEachRemaining(Consumer<? super SplittableGenerator> consumer)2281             public void forEachRemaining(Consumer<? super SplittableGenerator> consumer) {
2282                 Objects.requireNonNull(consumer);
2283                 long i = index, f = fence;
2284                 if (i < f) {
2285                     index = f;
2286                     SplittableGenerator c = constructingGenerator;
2287                     SplittableGenerator r = generatingGenerator;
2288                     do {
2289                         consumer.accept(c.split(r));
2290                     } while (++i < f);
2291                 }
2292             }
2293         }
2294 
2295     }
2296 
2297     /**
2298      * This class provides much of the implementation of the
2299      * {@link SplittableGenerator} interface, to minimize the effort required to
2300      * implement this interface. It is similar to the class
2301      * {@link AbstractSplittableGenerator} but makes use of the brine technique
2302      * for ensuring that distinct generators created by a single call to a
2303      * {@link SplittableGenerator#splits() splits}() method have distinct state
2304      * cycles.
2305      *
2306      * <p> To implement a pseudorandom number generator, the programmer needs
2307      * only to extend this class and provide implementations for the methods
2308      * {@link RandomGenerator#nextInt() nextInt}(),
2309      * {@link RandomGenerator#nextLong() nextLong}(),
2310      * {@link RandomSplitsSpliteratorWithSalt#split(SplittableGenerator, long) split}(splittable, brine).
2311      *
2312      * <p> The programmer should generally provide at least three constructors:
2313      * one that takes no arguments, one that accepts a {@code long} seed value,
2314      * and one that accepts an array of seed {@code byte} values. This class
2315      * provides a public {@link RandomSupport#initialSeed() initialSeed}()
2316      * method that may be useful in initializing some static state from which to
2317      * derive defaults seeds for use by the no-argument constructor.
2318      *
2319      * <p> For the stream methods (such as {@link RandomGenerator#ints() ints}()
2320      * and {@link SplittableGenerator#splits() splits}()), this class provides
2321      * {@link Spliterator}-based implementations that allow parallel execution
2322      * when appropriate.
2323      *
2324      * <p> The documentation for each non-abstract method in this class
2325      * describes its implementation in detail. Each of these methods may be
2326      * overridden if the pseudorandom number generator being implemented
2327      * admits a more efficient implementation.
2328      *
2329      * @since 17
2330      */
2331     public abstract static class AbstractSplittableWithBrineGenerator
2332             extends AbstractSplittableGenerator {
2333 
2334         /*
2335          * Implementation Overview.
2336          *
2337          * This class provides most of the "user API" methods needed to
2338          * satisfy the interface SplittableGenerator.  Most of these methods
2339          * are in turn inherited from AbstractSplittableGenerator and the non-public class
2340          * AbstractSpliteratorGenerator; this class provides four versions of the
2341          * splits method and defines the spliterators necessary to support
2342          * them.
2343          *
2344          * File organization: First the non-public methods needed by the class
2345          * AbstractSplittableWithBrineGenerator, then the main public methods,
2346          * followed by some custom spliterator classes needed for stream methods.
2347          */
2348 
2349         /**
2350          * Explicit constructor.
2351          */
AbstractSplittableWithBrineGenerator()2352         protected AbstractSplittableWithBrineGenerator() {
2353         }
2354 
2355         // The salt consists groups of bits each SALT_SHIFT in size, starting from
2356         // the left-hand (high-order) end of the word.  We can regard them as
2357         // digits base (1 << SALT_SHIFT).  If SALT_SHIFT does not divide 64
2358         // evenly, then any leftover bits at the low end of the word are zero.
2359         // The lowest digit of the salt is set to the largest possible digit
2360         // (all 1-bits, or ((1 << SALT_SHIFT) - 1)); all other digits are set
2361         // to a randomly chosen value less than that largest possible digit.
2362         // The salt may be shifted left by SALT_SHIFT any number of times.
2363         // If any salt remains in the word, its right-hand end can be identified
2364         // by searching from left to right for an occurrence of a digit that is
2365         // all 1-bits (not that we ever do that; this is simply a proof that one
2366         // can identify the boundary between the salt and the index if any salt
2367         // remains in the word).  The idea is that before computing the bitwise OR
2368         // of an index and the salt, one can first check to see whether the
2369         // bitwise AND is nonzero; if so, one can shift the salt left by
2370         // SALT_SHIFT and try again.  In this way, when the bitwise OR is
2371         // computed, if the salt is nonzero then its rightmost 1-bit is to the
2372         // left of the leftmost 1-bit of the index.
2373 
2374         // We need 2 <= SALT_SHIFT <= 63 (3 through 8 are good values; 4 is probably best)
2375         static final int SALT_SHIFT = 4;
2376 
2377         // Methods required by class AbstractSpliteratorGenerator (override)
makeSplitsSpliterator(long index, long fence, SplittableGenerator source)2378         Spliterator<SplittableGenerator> makeSplitsSpliterator(long index, long fence, SplittableGenerator source) {
2379             // This little algorithm to generate a new salt value is carefully
2380             // designed to work even if SALT_SHIFT does not evenly divide 64
2381             // (the number of bits in a long value).
2382             long bits = nextLong();
2383             long multiplier = (1L << SALT_SHIFT) - 1;
2384             long salt = multiplier << (64 - SALT_SHIFT);
2385             while ((salt & multiplier) == 0) {
2386                 long digit = Math.multiplyHigh(bits, multiplier);
2387                 salt = (salt >>> SALT_SHIFT) | (digit << (64 - SALT_SHIFT));
2388                 bits *= multiplier;
2389             }
2390             // This is the point at which newly generated salt gets injected into
2391             // the root of a newly created brine-generating splits-spliterator.
2392             return new RandomSplitsSpliteratorWithSalt(source, index, fence, this, salt);
2393         }
2394 
2395         /* ---------------- public methods ---------------- */
2396 
2397         // Stream methods for splitting
2398 
2399         /**
2400          * Constructs and returns a new instance of
2401          * {@link AbstractSplittableWithBrineGenerator} that shares no mutable
2402          * state with this instance. However, with very high probability, the
2403          * set of values collectively generated by the two objects should have
2404          * the same statistical properties as if the same quantity of values
2405          * were generated by a single thread using a single may be
2406          * {@link AbstractSplittableWithBrineGenerator} object. Either or both
2407          * of the two objects further split using the
2408          * {@link SplittableGenerator#split() split}() method, and the same
2409          * expected statistical properties apply to the entire set of generators
2410          * constructed by such recursive splitting.
2411          *
2412          * @param brine a long value, of which the low 63 bits provide a unique id
2413          * among calls to this method for constructing a single series of Generator objects.
2414          *
2415          * @return the new {@code AbstractSplittableWithBrineGenerator} instance
2416          */
split(long brine)2417         public SplittableGenerator split(long brine) {
2418             return this.split(this, brine);
2419         }
2420 
2421         @Override
split(SplittableGenerator source)2422         public SplittableGenerator split(SplittableGenerator source) {
2423             // It's a one-off: supply randomly chosen brine
2424             return this.split(source, source.nextLong());
2425         }
2426 
split(SplittableGenerator source, long brine)2427         public abstract SplittableGenerator split(SplittableGenerator source, long brine);
2428 
2429 
2430         /* ---------------- spliterator ---------------- */
2431         /**
2432          * Alternate spliterator for stream of generators of type
2433          * SplittableGenerator. We multiplex the two versions into one class by
2434          * treating "infinite" as equivalent to Long.MAX_VALUE. For splits, it
2435          * uses the standard divide-by-two approach.
2436          *
2437          * <p> This differs from
2438          * {@link AbstractSplittableGenerator.RandomSplitsSpliterator} in that it
2439          * provides a brine argument (a mixture of salt and an index) when
2440          * calling the {@link SplittableGenerator#split() split}() method.
2441          */
2442         static class RandomSplitsSpliteratorWithSalt
2443                 extends RandomSpliterator implements Spliterator<SplittableGenerator> {
2444 
2445             final SplittableGenerator generatingGenerator;
2446             final AbstractSplittableWithBrineGenerator constructingGenerator;
2447             long salt;
2448 
2449             // Important invariant: 0 <= index <= fence
2450 
2451             // Important invariant: if salt and index are both nonzero,
2452             // the rightmost 1-bit of salt is to the left of the leftmost 1-bit of index.
2453             // If necessary, the salt can be leftshifted by SALT_SHIFT as many times as
2454             // necessary to maintain the invariant.
2455 
RandomSplitsSpliteratorWithSalt(SplittableGenerator generatingGenerator, long index, long fence, AbstractSplittableWithBrineGenerator constructingGenerator, long salt)2456             RandomSplitsSpliteratorWithSalt(SplittableGenerator generatingGenerator, long index, long fence,
2457                                             AbstractSplittableWithBrineGenerator constructingGenerator, long salt) {
2458                 super(index, fence);
2459                 this.generatingGenerator = generatingGenerator;
2460                 this.constructingGenerator = constructingGenerator;
2461                 while ((salt != 0) && (Long.compareUnsigned(salt & -salt, index) <= 0)) {
2462                     salt = salt << SALT_SHIFT;
2463                 }
2464                 this.salt = salt;
2465             }
2466 
trySplit()2467             public Spliterator<SplittableGenerator> trySplit() {
2468                 long i = index, m = (i + fence) >>> 1;
2469                 if (m <= i) return null;
2470                 RandomSplitsSpliteratorWithSalt result =
2471                         new RandomSplitsSpliteratorWithSalt(generatingGenerator.split(), i, m, constructingGenerator, salt);
2472                 index = m;
2473                 while ((salt != 0) && (Long.compareUnsigned(salt & -salt, index) <= 0)) {
2474                     salt = salt << SALT_SHIFT;
2475                 }
2476                 return result;
2477             }
2478 
tryAdvance(Consumer<? super SplittableGenerator> consumer)2479             public boolean tryAdvance(Consumer<? super SplittableGenerator> consumer) {
2480                 Objects.requireNonNull(consumer);
2481                 long i = index, f = fence;
2482                 if (i < f) {
2483                     consumer.accept(constructingGenerator.split(generatingGenerator, salt | i));
2484                     ++i;
2485                     index = i;
2486                     if ((i & salt) != 0) salt <<= SALT_SHIFT;
2487                     return true;
2488                 }
2489                 return false;
2490             }
2491 
forEachRemaining(Consumer<? super SplittableGenerator> consumer)2492             public void forEachRemaining(Consumer<? super SplittableGenerator> consumer) {
2493                 Objects.requireNonNull(consumer);
2494                 long i = index, f = fence;
2495                 if (i < f) {
2496                     index = f;
2497                     AbstractSplittableWithBrineGenerator c = constructingGenerator;
2498                     SplittableGenerator r = generatingGenerator;
2499                     do {
2500                         consumer.accept(c.split(r, salt | i));
2501                         ++i;
2502                         if ((i & salt) != 0) salt <<= SALT_SHIFT;
2503                     } while (i < f);
2504                 }
2505             }
2506         }
2507     }
2508 
2509     /**
2510      * Implementation support for modified-ziggurat implementation of
2511      * nextExponential()
2512      *
2513      * <p> This Java class was generated automatically by a program
2514      * `create_ziggurat_tables.c`.
2515      *
2516      * <p> Fraction of the area under the curve that lies outside the layer
2517      * boxes: 0.0156 Fraction of non-box area that lies in the tail of the
2518      * distribution: 0.0330
2519      */
2520     static final class DoubleZigguratTables {
2521 
2522         static final int exponentialNumberOfLayers = 252;
2523         static final int exponentialLayerMask = 0xff;
2524         static final int exponentialAliasMask = 0xff;
2525         static final int exponentialSignCorrectionMask = 0xff;
2526         static final double exponentialX0 = 7.56927469414806264;
2527         static final long exponentialConvexMargin = 853965788476313645L;   // unscaled convex margin = 0.0926
2528 
2529         // exponential_X[i] = length of ziggurat layer i for exponential distribution, scaled by 2**(-63)
2530         static final double[] exponentialX = {      // 253 entries, which is exponential_number_of_layers+1
2531                 8.2066240675348816e-19,  7.3973732351607284e-19,  6.9133313377915293e-19,  6.5647358820964533e-19,
2532                 6.2912539959818508e-19,  6.0657224129604964e-19,  5.8735276103737269e-19,  5.7058850528536941e-19,
2533                 5.5570945691622390e-19,  5.4232438903743953e-19,  5.3015297696508776e-19,  5.1898739257708062e-19,
2534                 5.0866922617998330e-19,  4.9907492938796469e-19,  4.9010625894449536e-19,  4.8168379010649187e-19,
2535                 4.7374238653644714e-19,  4.6622795807196824e-19,  4.5909509017784048e-19,  4.5230527790658154e-19,
2536                 4.4582558816353960e-19,  4.3962763126368381e-19,  4.3368675967106470e-19,  4.2798143618469714e-19,
2537                 4.2249273027064889e-19,  4.1720391253464110e-19,  4.1210012522465616e-19,  4.0716811225869233e-19,
2538                 4.0239599631006903e-19,  3.9777309342877357e-19,  3.9328975785334499e-19,  3.8893725129310323e-19,
2539                 3.8470763218720385e-19,  3.8059366138180143e-19,  3.7658872138544730e-19,  3.7268674692030177e-19,
2540                 3.6888216492248162e-19,  3.6516984248800068e-19,  3.6154504153287473e-19,  3.5800337915318032e-19,
2541                 3.5454079284533432e-19,  3.5115350988784242e-19,  3.4783802030030962e-19,  3.4459105288907336e-19,
2542                 3.4140955396563316e-19,  3.3829066838741162e-19,  3.3523172262289001e-19,  3.3223020958685874e-19,
2543                 3.2928377502804472e-19,  3.2639020528202049e-19,  3.2354741622810815e-19,  3.2075344331080789e-19,
2544                 3.1800643250478609e-19,  3.1530463211820845e-19,  3.1264638534265134e-19,  3.1003012346934211e-19,
2545                 3.0745435970137301e-19,  3.0491768350005559e-19,  3.0241875541094565e-19,  2.9995630232144550e-19,
2546                 2.9752911310742592e-19,  2.9513603463113224e-19,  2.9277596805684267e-19,  2.9044786545442563e-19,
2547                 2.8815072666416712e-19,  2.8588359639906928e-19,  2.8364556156331615e-19,  2.8143574876779799e-19,
2548                 2.7925332202553125e-19,  2.7709748061152879e-19,  2.7496745707320232e-19,  2.7286251537873397e-19,
2549                 2.7078194919206054e-19,  2.6872508026419050e-19,  2.6669125693153442e-19,  2.6467985271278891e-19,
2550                 2.6269026499668434e-19,  2.6072191381359757e-19,  2.5877424068465143e-19,  2.5684670754248168e-19,
2551                 2.5493879571835479e-19,  2.5305000499077481e-19,  2.5117985269112710e-19,  2.4932787286227806e-19,
2552                 2.4749361546638660e-19,  2.4567664563848669e-19,  2.4387654298267842e-19,  2.4209290090801527e-19,
2553                 2.4032532600140538e-19,  2.3857343743505147e-19,  2.3683686640614648e-19,  2.3511525560671253e-19,
2554                 2.3340825872163284e-19,  2.3171553995306794e-19,  2.3003677356958333e-19,  2.2837164347843482e-19,
2555                 2.2671984281957174e-19,  2.2508107358001938e-19,  2.2345504622739592e-19,  2.2184147936140775e-19,
2556                 2.2024009938224424e-19,  2.1865064017486842e-19,  2.1707284280826716e-19,  2.1550645524878675e-19,
2557                 2.1395123208673778e-19,  2.1240693427550640e-19,  2.1087332888245875e-19,  2.0935018885097035e-19,
2558                 2.0783729277295508e-19,  2.0633442467130712e-19,  2.0484137379170616e-19,  2.0335793440326865e-19,
2559                 2.0188390560756090e-19,  2.0041909115551697e-19,  1.9896329927183254e-19,  1.9751634248643090e-19,
2560                 1.9607803747261946e-19,  1.9464820489157862e-19,  1.9322666924284314e-19,  1.9181325872045647e-19,
2561                 1.9040780507449479e-19,  1.8901014347767504e-19,  1.8762011239677479e-19,  1.8623755346860768e-19,
2562                 1.8486231138030984e-19,  1.8349423375370566e-19,  1.8213317103353295e-19,  1.8077897637931708e-19,
2563                 1.7943150556069476e-19,  1.7809061685599652e-19,  1.7675617095390567e-19,  1.7542803085801941e-19,
2564                 1.7410606179414531e-19,  1.7279013112017240e-19,  1.7148010823836362e-19,  1.7017586450992059e-19,
2565                 1.6887727317167824e-19,  1.6758420925479093e-19,  1.6629654950527621e-19,  1.6501417230628659e-19,
2566                 1.6373695760198277e-19,  1.6246478682288560e-19,  1.6119754281258616e-19,  1.5993510975569615e-19,
2567                 1.5867737310692309e-19,  1.5742421952115544e-19,  1.5617553678444595e-19,  1.5493121374578016e-19,
2568                 1.5369114024951992e-19,  1.5245520706841019e-19,  1.5122330583703858e-19,  1.4999532898563561e-19,
2569                 1.4877116967410352e-19,  1.4755072172615974e-19,  1.4633387956347966e-19,  1.4512053813972103e-19,
2570                 1.4391059287430991e-19,  1.4270393958586506e-19,  1.4150047442513381e-19,  1.4030009380730888e-19,
2571                 1.3910269434359025e-19,  1.3790817277185197e-19,  1.3671642588626657e-19,  1.3552735046573446e-19,
2572                 1.3434084320095729e-19,  1.3315680061998685e-19,  1.3197511901207148e-19,  1.3079569434961214e-19,
2573                 1.2961842220802957e-19,  1.2844319768333099e-19,  1.2726991530715219e-19,  1.2609846895903523e-19,
2574                 1.2492875177568625e-19,  1.2376065605693940e-19,  1.2259407316813331e-19,  1.2142889343858445e-19,
2575                 1.2026500605581765e-19,  1.1910229895518744e-19,  1.1794065870449425e-19,  1.1677997038316715e-19,
2576                 1.1562011745554883e-19,  1.1446098163777869e-19,  1.1330244275772562e-19,  1.1214437860737343e-19,
2577                 1.1098666478700728e-19,  1.0982917454048923e-19,  1.0867177858084351e-19,  1.0751434490529747e-19,
2578                 1.0635673859884002e-19,  1.0519882162526621e-19,  1.0404045260457141e-19,  1.0288148657544097e-19,
2579                 1.0172177474144965e-19,  1.0056116419943559e-19,  9.9399497648346677e-20,  9.8236613076667446e-20,
2580                 9.7072343426320094e-20,  9.5906516230690634e-20,  9.4738953224154196e-20,  9.3569469920159036e-20,
2581                 9.2397875154569468e-20,  9.1223970590556472e-20,  9.0047550180852874e-20,  8.8868399582647627e-20,
2582                 8.7686295519767450e-20,  8.6501005086071005e-20,  8.5312284983141187e-20,  8.4119880684385214e-20,
2583                 8.2923525516513420e-20,  8.1722939648034506e-20,  8.0517828972839211e-20,  7.9307883875099226e-20,
2584                 7.8092777859524425e-20,  7.6872166028429042e-20,  7.5645683383965122e-20,  7.4412942930179128e-20,
2585                 7.3173533545093332e-20,  7.1927017587631075e-20,  7.0672928197666785e-20,  6.9410766239500362e-20,
2586                 6.8139996829256425e-20,  6.6860045374610234e-20,  6.5570293040210081e-20,  6.4270071533368528e-20,
2587                 6.2958657080923559e-20,  6.1635263438143136e-20,  6.0299033732151700e-20,  5.8949030892850181e-20,
2588                 5.7584226359885930e-20,  5.6203486669597397e-20,  5.4805557413499315e-20,  5.3389043909003295e-20,
2589                 5.1952387717989917e-20,  5.0493837866338355e-20,  4.9011415222629489e-20,  4.7502867933366117e-20,
2590                 4.5965615001265455e-20,  4.4396673897997565e-20,  4.2792566302148588e-20,  4.1149193273430015e-20,
2591                 3.9461666762606287e-20,  3.7724077131401685e-20,  3.5929164086204360e-20,  3.4067836691100565e-20,
2592                 3.2128447641564046e-20,  3.0095646916399994e-20,  2.7948469455598328e-20,  2.5656913048718645e-20,
2593                 2.3175209756803909e-20,  2.0426695228251291e-20,  1.7261770330213485e-20,  1.3281889259442578e-20,
2594                 0.0000000000000000e+00 };
2595 
2596         // exponential_Y[i] = value of the exponential distribution function at exponential_X[i], scaled by 2**(-63)
2597         static final double[] exponentialY = {      // 253 entries, which is exponential_number_of_layers+1
2598                 5.5952054951127360e-23,  1.1802509982703313e-22,  1.8444423386735829e-22,  2.5439030466698309e-22,
2599                 3.2737694311509334e-22,  4.0307732132706715e-22,  4.8125478319495115e-22,  5.6172914896583308e-22,
2600                 6.4435820540443526e-22,  7.2902662343463681e-22,  8.1563888456321941e-22,  9.0411453683482223e-22,
2601                 9.9438488486399206e-22,  1.0863906045969114e-21,  1.1800799775461269e-21,  1.2754075534831208e-21,
2602                 1.3723331176377290e-21,  1.4708208794375214e-21,  1.5708388257440445e-21,  1.6723581984374566e-21,
2603                 1.7753530675030514e-21,  1.8797999785104595e-21,  1.9856776587832504e-21,  2.0929667704053244e-21,
2604                 2.2016497009958240e-21,  2.3117103852306179e-21,  2.4231341516125464e-21,  2.5359075901420891e-21,
2605                 2.6500184374170538e-21,  2.7654554763660391e-21,  2.8822084483468604e-21,  3.0002679757547711e-21,
2606                 3.1196254936130377e-21,  3.2402731888801749e-21,  3.3622039464187092e-21,  3.4854113007409036e-21,
2607                 3.6098893927859475e-21,  3.7356329310971768e-21,  3.8626371568620053e-21,  3.9908978123552837e-21,
2608                 4.1204111123918948e-21,  4.2511737184488913e-21,  4.3831827151633737e-21,  4.5164355889510656e-21,
2609                 4.6509302085234806e-21,  4.7866648071096003e-21,  4.9236379662119969e-21,  5.0618486007478993e-21,
2610                 5.2012959454434732e-21,  5.3419795423648946e-21,  5.4838992294830959e-21,  5.6270551301806347e-21,
2611                 5.7714476436191935e-21,  5.9170774358950678e-21,  6.0639454319177027e-21,  6.2120528079531677e-21,
2612                 6.3614009847804375e-21,  6.5119916214136427e-21,  6.6638266093481696e-21,  6.8169080672926277e-21,
2613                 6.9712383363524377e-21,  7.1268199756340822e-21,  7.2836557582420336e-21,  7.4417486676430174e-21,
2614                 7.6011018943746355e-21,  7.7617188330775411e-21,  7.9236030798322572e-21,  8.0867584297834842e-21,
2615                 8.2511888750363333e-21,  8.4168986028103258e-21,  8.5838919938383098e-21,  8.7521736209986459e-21,
2616                 8.9217482481700712e-21,  9.0926208292996504e-21,  9.2647965076751277e-21,  9.4382806153938292e-21,
2617                 9.6130786730210328e-21,  9.7891963894314161e-21,  9.9666396618278840e-21,  1.0145414575932636e-20,
2618                 1.0325527406345955e-20,  1.0506984617068672e-20,  1.0689792862184811e-20,  1.0873958986701341e-20,
2619                 1.1059490027542400e-20,  1.1246393214695825e-20,  1.1434675972510121e-20,  1.1624345921140471e-20,
2620                 1.1815410878142659e-20,  1.2007878860214202e-20,  1.2201758085082226e-20,  1.2397056973538040e-20,
2621                 1.2593784151618565e-20,  1.2791948452935152e-20,  1.2991558921150600e-20,  1.3192624812605428e-20,
2622                 1.3395155599094805e-20,  1.3599160970797774e-20,  1.3804650839360727e-20,  1.4011635341137284e-20,
2623                 1.4220124840587164e-20,  1.4430129933836705e-20,  1.4641661452404201e-20,  1.4854730467093280e-20,
2624                 1.5069348292058084e-20,  1.5285526489044050e-20,  1.5503276871808626e-20,  1.5722611510726402e-20,
2625                 1.5943542737583543e-20,  1.6166083150566702e-20,  1.6390245619451956e-20,  1.6616043290999594e-20,
2626                 1.6843489594561079e-20,  1.7072598247904713e-20,  1.7303383263267072e-20,  1.7535858953637607e-20,
2627                 1.7770039939284241e-20,  1.8005941154528286e-20,  1.8243577854777398e-20,  1.8482965623825808e-20,
2628                 1.8724120381431627e-20,  1.8967058391181452e-20,  1.9211796268653192e-20,  1.9458350989888484e-20,
2629                 1.9706739900186868e-20,  1.9956980723234356e-20,  2.0209091570579904e-20,  2.0463090951473895e-20,
2630                 2.0718997783083593e-20,  2.0976831401101350e-20,  2.1236611570762130e-20,  2.1498358498287976e-20,
2631                 2.1762092842777868e-20,  2.2027835728562592e-20,  2.2295608758045219e-20,  2.2565434025049041e-20,
2632                 2.2837334128696004e-20,  2.3111332187840010e-20,  2.3387451856080863e-20,  2.3665717337386111e-20,
2633                 2.3946153402349610e-20,  2.4228785405117410e-20,  2.4513639301013211e-20,  2.4800741664897764e-20,
2634                 2.5090119710298442e-20,  2.5381801309347597e-20,  2.5675815013570500e-20,  2.5972190075566336e-20,
2635                 2.6270956471628253e-20,  2.6572144925351523e-20,  2.6875786932281841e-20,  2.7181914785659148e-20,
2636                 2.7490561603315974e-20,  2.7801761355793055e-20,  2.8115548895739172e-20,  2.8431959988666534e-20,
2637                 2.8751031345137833e-20,  2.9072800654466307e-20,  2.9397306620015486e-20,  2.9724588996191657e-20,
2638                 3.0054688627228112e-20,  3.0387647487867642e-20,  3.0723508726057078e-20,  3.1062316707775905e-20,
2639                 3.1404117064129991e-20,  3.1748956740850969e-20,  3.2096884050352357e-20,  3.2447948726504914e-20,
2640                 3.2802201982306013e-20,  3.3159696570631373e-20,  3.3520486848272230e-20,  3.3884628843476888e-20,
2641                 3.4252180327233346e-20,  3.4623200888548644e-20,  3.4997752014001677e-20,  3.5375897171869060e-20,
2642                 3.5757701901149035e-20,  3.6143233905835799e-20,  3.6532563154827400e-20,  3.6925761987883572e-20,
2643                 3.7322905228086981e-20,  3.7724070301302117e-20,  3.8129337363171041e-20,  3.8538789434235234e-20,
2644                 3.8952512543827862e-20,  3.9370595883442399e-20,  3.9793131970351439e-20,  4.0220216822325769e-20,
2645                 4.0651950144388133e-20,  4.1088435528630944e-20,  4.1529780668232712e-20,  4.1976097586926582e-20,
2646                 4.2427502885307452e-20,  4.2884118005513604e-20,  4.3346069515987453e-20,  4.3813489418210257e-20,
2647                 4.4286515477520838e-20,  4.4765291580372353e-20,  4.5249968120658306e-20,  4.5740702418054417e-20,
2648                 4.6237659171683015e-20,  4.6741010952818368e-20,  4.7250938740823415e-20,  4.7767632507051219e-20,
2649                 4.8291291852069895e-20,  4.8822126702292804e-20,  4.9360358072933852e-20,  4.9906218905182021e-20,
2650                 5.0459954986625539e-20,  5.1021825965285324e-20,  5.1592106469178258e-20,  5.2171087345169234e-20,
2651                 5.2759077033045284e-20,  5.3356403093325858e-20,  5.3963413910399511e-20,  5.4580480596259246e-20,
2652                 5.5207999124535584e-20,  5.5846392729873830e-20,  5.6496114614193770e-20,  5.7157651009290713e-20,
2653                 5.7831524654956632e-20,  5.8518298763794323e-20,  5.9218581558791713e-20,  5.9933031488338700e-20,
2654                 6.0662363246796887e-20,  6.1407354758435000e-20,  6.2168855320499763e-20,  6.2947795150103727e-20,
2655                 6.3745196643214394e-20,  6.4562187737537985e-20,  6.5400017881889097e-20,  6.6260077263309343e-20,
2656                 6.7143920145146620e-20,  6.8053293447301698e-20,  6.8990172088133000e-20,  6.9956803158564498e-20,
2657                 7.0955761794878430e-20,  7.1990022788945080e-20,  7.3063053739105458e-20,  7.4178938266266893e-20,
2658                 7.5342542134173124e-20,  7.6559742171142969e-20,  7.7837749863412850e-20,  7.9185582674029512e-20,
2659                 8.0614775537353300e-20,  8.2140502769818073e-20,  8.3783445978280519e-20,  8.5573129249678161e-20,
2660                 8.7554459669590100e-20,  8.9802388057706877e-20,  9.2462471421151086e-20,  9.5919641344951721e-20,
2661                 1.0842021724855044e-19 };
2662 
2663         // alias_threshold[j] is a threshold for the probability mass function that has been
2664         // scaled by (2**64 - 1), translated by -(2**63), and represented as a long value;
2665         // in this way it can be directly compared to a randomly chosen long value.
2666         static final long[] exponentialAliasThreshold = {    // 256 entries
2667                 9223372036854775807L,  1623796909450829958L,  2664290944894281002L,  7387971354164055035L,
2668                 6515064486552722205L,  8840508362680707094L,  6099647593382923818L,  7673130333659514446L,
2669                 6220332867583438718L,  5045979640552814279L,  4075305837223956071L,  3258413672162525964L,
2670                 2560664887087763045L,  1957224924672900129L,  1429800935350578000L,   964606309710808688L,
2671                 551043923599587587L,   180827629096889062L,  -152619738120023316L,  -454588624410291246L,
2672                 -729385126147774679L,  -980551509819444511L, -1211029700667463575L, -1423284293868546830L,
2673                 -1619396356369066372L, -1801135830956194794L, -1970018048575634032L, -2127348289059688469L,
2674                 -2274257249303687482L, -2411729520096654942L, -2540626634159182211L, -2661705860113406183L,
2675                 -2775635634532464842L, -2883008316030448462L, -2984350790383654449L, -3080133339198118132L,
2676                 -3170777096303105047L, -3256660348483802362L, -3338123885075135933L, -3415475560473298752L,
2677                 -3488994201966444258L, -3558932970354456420L, -3625522261068040742L, -3688972217741991689L,
2678                 -3749474917563779627L, -3807206277531072172L, -3862327722496826830L, -3914987649156779312L,
2679                 -3965322714631864882L, -4013458973776911635L, -4059512885612766613L, -4103592206186240662L,
2680                 -4145796782586127736L, -4186219260694346585L, -4224945717447274810L, -4262056226866285147L,
2681                 -4297625367836519229L, -4331722680528536958L, -4364413077437472159L, -4395757214229421760L,
2682                 -4425811824915119137L, -4454630025296932322L, -4482261588141294467L, -4508753193105275908L,
2683                 -4534148654077813412L, -4558489126279965349L, -4581813295192216486L, -4604157549138252679L,
2684                 -4625556137145250151L, -4646041313519109096L, -4665643470413305673L, -4684391259530342697L,
2685                 -4702311703971745066L, -4719430301145102986L, -4735771117539946027L, -4751356876102086987L,
2686                 -4766209036859150188L, -4780347871385996716L, -4793792531638885869L, -4806561113635132333L,
2687                 -4818670716409312334L, -4830137496634465358L, -4840976719260854030L, -4851202804490332239L,
2688                 -4860829371376476047L, -4869869278311650511L, -4878334660640770576L, -4886236965617426832L,
2689                 -4893586984900802224L, -4900394884772702384L, -4906670234238884945L, -4912422031164489009L,
2690                 -4917658726580135697L, -4922388247283531793L, -4926618016851042065L, -4930354975163351025L,
2691                 -4933605596540650674L, -4936375906575303186L, -4938671497741357106L, -4940497543854583186L,
2692                 -4941858813449628882L, -4942759682136114354L, -4943204143989086194L, -4943195822025527282L,
2693                 -4942737977813222130L, -4941833520255011698L, -4940485013586759090L, -4938694684624342322L,
2694                 -4936464429291795314L, -4933795818458824946L, -4930690103114057265L, -4927148218896863345L,
2695                 -4923170790008291569L, -4918758132519196401L, -4913910257091661489L, -4908626871126522161L,
2696                 -4902907380349538608L, -4896750889844272240L, -4890156204540530416L, -4883121829162570096L,
2697                 -4875645967641780528L, -4867726521994909999L, -4859361090668119087L, -4850546966345102383L,
2698                 -4841281133215538414L, -4831560263698491374L, -4821380714613452974L, -4810738522790065581L,
2699                 -4799629400105481389L, -4788048727936296621L, -4775991551010524588L, -4763452570642113772L,
2700                 -4750426137329493931L, -4736906242696388587L, -4722886510751367403L, -4708360188440104938L,
2701                 -4693320135461420394L, -4677758813316098089L, -4661668273553495721L, -4645040145179234152L,
2702                 -4627865621182771687L, -4610135444140936871L, -4591839890849352486L, -4572968755929944934L,
2703                 -4553511334358213029L, -4533456402849109028L, -4512792200036270244L, -4491506405372580067L,
2704                 -4469586116675401954L, -4447017826233099938L, -4423787395382284961L, -4399880027458416864L,
2705                 -4375280239014124063L, -4349971829190464606L, -4323937847117722654L, -4297160557210942813L,
2706                 -4269621402214950684L, -4241300963840750107L, -4212178920821854874L, -4182234004204445017L,
2707                 -4151443949668869272L, -4119785446662323159L, -4087234084103169942L, -4053764292396165205L,
2708                 -4019349281473092435L, -3983960974549686930L, -3947569937258414993L, -3910145301787337104L,
2709                 -3871654685619049615L, -3832064104425389837L, -3791337878631529676L, -3749438533114328651L,
2710                 -3706326689447979465L, -3661960950051859912L, -3616297773528542022L, -3569291340409179909L,
2711                 -3520893408440947267L, -3471053156460649921L, -3419717015797783872L, -3366828488034801534L,
2712                 -3312327947826461820L, -3256152429334023226L, -3198235394669709240L, -3138506482563174262L,
2713                 -3076891235255164340L, -3013310801389715890L, -2947681612411392816L, -2879915029671670702L,
2714                 -2809916959107519276L, -2737587429961855017L, -2662820133571332903L, -2585501917733374884L,
2715                 -2505512231579392929L, -2422722515205190175L, -2336995527534106140L, -2248184604988712345L,
2716                 -2156132842510782614L, -2060672187261016979L, -1961622433929380112L, -1858790108950090508L,
2717                 -1751967229002904073L, -1640929916937134981L, -1525436855617591297L, -1405227557075245821L,
2718                 -1280020420662651897L, -1149510549536605301L, -1013367289578706928L,  -871231448632089708L,
2719                 -722712146453677415L,  -567383236774421729L,  -404779231966956764L,  -234390647591531478L,
2720                 -55658667960121553L,   132030985907831093L,   329355128892817467L,   537061298001091010L,
2721                 755977262693561929L,   987022116608030929L,  1231219266829437401L,  1489711711346524770L,
2722                 1763780090187559275L,  2054864117341782772L,  2364588157623782527L,  2694791916990482441L,
2723                 3047567482883491349L,  3425304305830820514L,  3830744187097285423L,  4267048975685836605L,
2724                 4737884547990014029L,  5247525842199011422L,  5800989391535342064L,  6404202162993303300L,
2725                 7064218894258526746L,  7789505049452354354L,  8590309807749425484L,  7643763810684501605L,
2726                 8891950541491453167L,  5457384281016234818L,  9083704440929285914L,  7976211653914461751L,
2727                 8178631350487124609L,  2821287825726757492L,  6322989683301736617L,  4309503753387630347L,
2728                 4685170734960191673L,  8404845967535252693L,  7330522972447610419L,  1960945799077061994L,
2729                 4742910674644933674L,  -751799822533438695L,  7023456603742021660L,  3843116882594755262L,
2730                 3927231442413889375L, -9223372036854775807L, -9223372036854775807L, -9223372036854775807L };
2731 
2732         static final byte[] exponentialAliasMap = {    // 256 entries
2733                 (byte)  0, (byte)  0, (byte)  1, (byte)235, (byte)  3, (byte)  4, (byte)  5, (byte)  0,
2734                 (byte)  0, (byte)  0, (byte)  0, (byte)  0, (byte)  0, (byte)  0, (byte)  0, (byte)  0,
2735                 (byte)  0, (byte)  0, (byte)  1, (byte)  1, (byte)  1, (byte)  1, (byte)  2, (byte)  2,
2736                 (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252,
2737                 (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252,
2738                 (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252,
2739                 (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252,
2740                 (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252,
2741                 (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252,
2742                 (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252,
2743                 (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252,
2744                 (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252,
2745                 (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252,
2746                 (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252,
2747                 (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252,
2748                 (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252,
2749                 (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252,
2750                 (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252,
2751                 (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252,
2752                 (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252,
2753                 (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252,
2754                 (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252,
2755                 (byte)252, (byte)251, (byte)251, (byte)251, (byte)251, (byte)251, (byte)251, (byte)251,
2756                 (byte)251, (byte)251, (byte)251, (byte)251, (byte)251, (byte)251, (byte)250, (byte)250,
2757                 (byte)250, (byte)250, (byte)250, (byte)250, (byte)250, (byte)249, (byte)249, (byte)249,
2758                 (byte)249, (byte)249, (byte)249, (byte)248, (byte)248, (byte)248, (byte)248, (byte)247,
2759                 (byte)247, (byte)247, (byte)247, (byte)246, (byte)246, (byte)246, (byte)245, (byte)245,
2760                 (byte)244, (byte)244, (byte)243, (byte)243, (byte)242, (byte)241, (byte)241, (byte)240,
2761                 (byte)239, (byte)237, (byte)  3, (byte)  3, (byte)  4, (byte)  4, (byte)  6, (byte)  0,
2762                 (byte)  0, (byte)  0, (byte)  0, (byte)236, (byte)237, (byte)238, (byte)239, (byte)240,
2763                 (byte)241, (byte)242, (byte)243, (byte)244, (byte)245, (byte)246, (byte)247, (byte)248,
2764                 (byte)249, (byte)250, (byte)251, (byte)252, (byte)  2, (byte)  0, (byte)  0, (byte)  0 };
2765 
2766         // Implementation support for modified-ziggurat implementation of nextGaussian()
2767 
2768         // Fraction of the area under the curve that lies outside the layer boxes: 0.0117
2769         // Fraction of non-box area that lies in the tail of the distribution: 0.0236
2770 
2771         static final int normalNumberOfLayers = 253;
2772         static final int normalLayerMask = 0xff;
2773         static final int normalAliasMask = 0xff;
2774         static final int normalSignCorrectionMask = 0xff;
2775         static final double normalX0 = 3.63600662550094578;
2776         static final int normalInflectionIndex = 204;
2777         static final long normalConvexMargin = 760463704284035183L;   // unscaled convex margin = 0.0824
2778         static final long normalConcaveMargin = 2269182951627976012L;   // unscaled concave margin = 0.2460
2779 
2780         // normal_X[i] = length of ziggurat layer i for normal distribution, scaled by 2**(-63)
2781         static final double[] normalX = {      // 254 entries, which is normal_number_of_layers+1
2782                 3.9421662825398133e-19,  3.7204945004119012e-19,  3.5827024480628678e-19,  3.4807476236540249e-19,
2783                 3.3990177171882136e-19,  3.3303778360340139e-19,  3.2709438817617550e-19,  3.2183577132495100e-19,
2784                 3.1710758541840432e-19,  3.1280307407034065e-19,  3.0884520655804019e-19,  3.0517650624107352e-19,
2785                 3.0175290292584600e-19,  2.9853983440705320e-19,  2.9550967462801797e-19,  2.9263997988491663e-19,
2786                 2.8991225869977476e-19,  2.8731108780226291e-19,  2.8482346327101335e-19,  2.8243831535194389e-19,
2787                 2.8014613964727031e-19,  2.7793871261807797e-19,  2.7580886921411212e-19,  2.7375032698308758e-19,
2788                 2.7175754543391047e-19,  2.6982561247538484e-19,  2.6795015188771505e-19,  2.6612724730440033e-19,
2789                 2.6435337927976633e-19,  2.6262537282028438e-19,  2.6094035335224142e-19,  2.5929570954331002e-19,
2790                 2.5768906173214726e-19,  2.5611823497719608e-19,  2.5458123593393361e-19,  2.5307623292372459e-19,
2791                 2.5160153867798400e-19,  2.5015559533646191e-19,  2.4873696135403158e-19,  2.4734430003079206e-19,
2792                 2.4597636942892726e-19,  2.4463201347912450e-19,  2.4331015411139206e-19,  2.4200978427132955e-19,
2793                 2.4072996170445879e-19,  2.3946980340903347e-19,  2.3822848067252674e-19,  2.3700521461931801e-19,
2794                 2.3579927220741330e-19,  2.3460996262069972e-19,  2.3343663401054455e-19,  2.3227867054673840e-19,
2795                 2.3113548974303765e-19,  2.3000654002704238e-19,  2.2889129852797606e-19,  2.2778926905921897e-19,
2796                 2.2669998027527321e-19,  2.2562298398527416e-19,  2.2455785360727260e-19,  2.2350418274933911e-19,
2797                 2.2246158390513294e-19,  2.2142968725296249e-19,  2.2040813954857555e-19,  2.1939660310297601e-19,
2798                 2.1839475483749618e-19,  2.1740228540916853e-19,  2.1641889840016519e-19,  2.1544430956570613e-19,
2799                 2.1447824613540345e-19,  2.1352044616350571e-19,  2.1257065792395107e-19,  2.1162863934653125e-19,
2800                 2.1069415749082026e-19,  2.0976698805483467e-19,  2.0884691491567363e-19,  2.0793372969963634e-19,
2801                 2.0702723137954107e-19,  2.0612722589717129e-19,  2.0523352580895635e-19,  2.0434594995315797e-19,
2802                 2.0346432313698148e-19,  2.0258847584216418e-19,  2.0171824394771313e-19,  2.0085346846857531e-19,
2803                 1.9999399530912015e-19,  1.9913967503040585e-19,  1.9829036263028144e-19,  1.9744591733545175e-19,
2804                 1.9660620240469857e-19,  1.9577108494251485e-19,  1.9494043572246307e-19,  1.9411412901962161e-19,
2805                 1.9329204245152935e-19,  1.9247405682708168e-19,  1.9166005600287074e-19,  1.9084992674649826e-19,
2806                 1.9004355860642340e-19,  1.8924084378793725e-19,  1.8844167703488436e-19,  1.8764595551677749e-19,
2807                 1.8685357872097450e-19,  1.8606444834960934e-19,  1.8527846822098793e-19,  1.8449554417517928e-19,
2808                 1.8371558398354868e-19,  1.8293849726199566e-19,  1.8216419538767393e-19,  1.8139259141898448e-19,
2809                 1.8062360001864453e-19,  1.7985713737964743e-19,  1.7909312115393845e-19,  1.7833147038364200e-19,
2810                 1.7757210543468428e-19,  1.7681494793266395e-19,  1.7605992070083140e-19,  1.7530694770004409e-19,
2811                 1.7455595397057217e-19,  1.7380686557563475e-19,  1.7305960954655264e-19,  1.7231411382940904e-19,
2812                 1.7157030723311378e-19,  1.7082811937877138e-19,  1.7008748065025788e-19,  1.6934832214591352e-19,
2813                 1.6861057563126349e-19,  1.6787417349268046e-19,  1.6713904869190636e-19,  1.6640513472135291e-19,
2814                 1.6567236556010242e-19,  1.6494067563053266e-19,  1.6420999975549115e-19,  1.6348027311594532e-19,
2815                 1.6275143120903661e-19,  1.6202340980646725e-19,  1.6129614491314931e-19,  1.6056957272604589e-19,
2816                 1.5984362959313479e-19,  1.5911825197242491e-19,  1.5839337639095554e-19,  1.5766893940370800e-19,
2817                 1.5694487755235889e-19,  1.5622112732380261e-19,  1.5549762510837070e-19,  1.5477430715767271e-19,
2818                 1.5405110954198330e-19,  1.5332796810709688e-19,  1.5260481843056974e-19,  1.5188159577726683e-19,
2819                 1.5115823505412761e-19,  1.5043467076406199e-19,  1.4971083695888395e-19,  1.4898666719118714e-19,
2820                 1.4826209446506113e-19,  1.4753705118554365e-19,  1.4681146910669830e-19,  1.4608527927820112e-19,
2821                 1.4535841199031451e-19,  1.4463079671711862e-19,  1.4390236205786415e-19,  1.4317303567630177e-19,
2822                 1.4244274423783481e-19,  1.4171141334433217e-19,  1.4097896746642792e-19,  1.4024532987312287e-19,
2823                 1.3951042255849034e-19,  1.3877416616527576e-19,  1.3803647990516385e-19,  1.3729728147547174e-19,
2824                 1.3655648697200824e-19,  1.3581401079782068e-19,  1.3506976556752901e-19,  1.3432366200692418e-19,
2825                 1.3357560884748263e-19,  1.3282551271542047e-19,  1.3207327801488087e-19,  1.3131880680481524e-19,
2826                 1.3056199866908076e-19,  1.2980275057923788e-19,  1.2904095674948608e-19,  1.2827650848312727e-19,
2827                 1.2750929400989213e-19,  1.2673919831340482e-19,  1.2596610294799512e-19,  1.2518988584399374e-19,
2828                 1.2441042110056523e-19,  1.2362757876504165e-19,  1.2284122459762072e-19,  1.2205121982017852e-19,
2829                 1.2125742084782245e-19,  1.2045967900166973e-19,  1.1965784020118020e-19,  1.1885174463419555e-19,
2830                 1.1804122640264091e-19,  1.1722611314162064e-19,  1.1640622560939109e-19,  1.1558137724540874e-19,
2831                 1.1475137369333185e-19,  1.1391601228549047e-19,  1.1307508148492592e-19,  1.1222836028063025e-19,
2832                 1.1137561753107903e-19,  1.1051661125053526e-19,  1.0965108783189755e-19,  1.0877878119905372e-19,
2833                 1.0789941188076655e-19,  1.0701268599703640e-19,  1.0611829414763286e-19,  1.0521591019102928e-19,
2834                 1.0430518990027552e-19,  1.0338576948035472e-19,  1.0245726392923699e-19,  1.0151926522209310e-19,
2835                 1.0057134029488235e-19,  9.9613028799672809e-20,  9.8643840599459914e-20,  9.7663252964755816e-20,
2836                 9.6670707427623454e-20,  9.5665606240866670e-20,  9.4647308380433213e-20,  9.3615125017323508e-20,
2837                 9.2568314370887282e-20,  9.1506075837638774e-20,  9.0427543267725716e-20,  8.9331777233763680e-20,
2838                 8.8217756102327883e-20,  8.7084365674892319e-20,  8.5930387109612162e-20,  8.4754482764244349e-20,
2839                 8.3555179508462343e-20,  8.2330848933585364e-20,  8.1079683729129853e-20,  7.9799669284133864e-20,
2840                 7.8488549286072745e-20,  7.7143783700934692e-20,  7.5762496979467566e-20,  7.4341413578485329e-20,
2841                 7.2876776807378431e-20,  7.1364245443525374e-20,  6.9798760240761066e-20,  6.8174368944799054e-20,
2842                 6.6483992986198539e-20,  6.4719110345162767e-20,  6.2869314813103699e-20,  6.0921687548281263e-20,
2843                 5.8859873575576818e-20,  5.6662675116090981e-20,  5.4301813630894571e-20,  5.1738171744494220e-20,
2844                 4.8915031722398545e-20,  4.5744741890755301e-20,  4.2078802568583416e-20,  3.7625986722404761e-20,
2845                 3.1628589805881879e-20,  0.0000000000000000e+00 };
2846 
2847         // normal_Y[i] = value of the normal distribution function at normal_X[i], scaled by 2**(-63)
2848         static final double[] normalY = {      // 254 entries, which is normal_number_of_layers+1
2849                 1.4598410796619063e-22,  3.0066613427942797e-22,  4.6129728815103466e-22,  6.2663350049234362e-22,
2850                 7.9594524761881544e-22,  9.6874655021705039e-22,  1.1446877002379439e-21,  1.3235036304379167e-21,
2851                 1.5049857692053131e-21,  1.6889653000719298e-21,  1.8753025382711626e-21,  2.0638798423695191e-21,
2852                 2.2545966913644708e-21,  2.4473661518801799e-21,  2.6421122727763533e-21,  2.8387681187879908e-21,
2853                 3.0372742567457284e-21,  3.2375775699986589e-21,  3.4396303157948780e-21,  3.6433893657997798e-21,
2854                 3.8488155868912312e-21,  4.0558733309492775e-21,  4.2645300104283590e-21,  4.4747557422305067e-21,
2855                 4.6865230465355582e-21,  4.8998065902775257e-21,  5.1145829672105489e-21,  5.3308305082046173e-21,
2856                 5.5485291167031758e-21,  5.7676601252690476e-21,  5.9882061699178461e-21,  6.2101510795442221e-21,
2857                 6.4334797782257209e-21,  6.6581781985713897e-21,  6.8842332045893181e-21,  7.1116325227957095e-21,
2858                 7.3403646804903092e-21,  7.5704189502886418e-21,  7.8017853001379744e-21,  8.0344543481570017e-21,
2859                 8.2684173217333118e-21,  8.5036660203915022e-21,  8.7401927820109521e-21,  8.9779904520281901e-21,
2860                 9.2170523553061439e-21,  9.4573722703928820e-21,  9.6989444059269430e-21,  9.9417633789758424e-21,
2861                 1.0185824195119818e-20,  1.0431122230114770e-20,  1.0677653212987396e-20,  1.0925413210432004e-20,
2862                 1.1174398612392891e-20,  1.1424606118728715e-20,  1.1676032726866302e-20,  1.1928675720361027e-20,
2863                 1.2182532658289373e-20,  1.2437601365406785e-20,  1.2693879923010674e-20,  1.2951366660454145e-20,
2864                 1.3210060147261461e-20,  1.3469959185800733e-20,  1.3731062804473644e-20,  1.3993370251385596e-20,
2865                 1.4256880988463136e-20,  1.4521594685988369e-20,  1.4787511217522902e-20,  1.5054630655196170e-20,
2866                 1.5322953265335218e-20,  1.5592479504415048e-20,  1.5863210015310328e-20,  1.6135145623830982e-20,
2867                 1.6408287335525592e-20,  1.6682636332737932e-20,  1.6958193971903124e-20,  1.7234961781071113e-20,
2868                 1.7512941457646084e-20,  1.7792134866331487e-20,  1.8072544037271070e-20,  1.8354171164377277e-20,
2869                 1.8637018603838945e-20,  1.8921088872801004e-20,  1.9206384648209468e-20,  1.9492908765815636e-20,
2870                 1.9780664219333857e-20,  2.0069654159747839e-20,  2.0359881894760859e-20,  2.0651350888385696e-20,
2871                 2.0944064760670539e-20,  2.1238027287557466e-20,  2.1533242400870487e-20,  2.1829714188430474e-20,
2872                 2.2127446894294597e-20,  2.2426444919118270e-20,  2.2726712820637798e-20,  2.3028255314272276e-20,
2873                 2.3331077273843558e-20,  2.3635183732413286e-20,  2.3940579883236352e-20,  2.4247271080830277e-20,
2874                 2.4555262842160330e-20,  2.4864560847940368e-20,  2.5175170944049622e-20,  2.5487099143065929e-20,
2875                 2.5800351625915997e-20,  2.6114934743643687e-20,  2.6430855019297323e-20,  2.6748119149937411e-20,
2876                 2.7066734008766247e-20,  2.7386706647381193e-20,  2.7708044298153558e-20,  2.8030754376735269e-20,
2877                 2.8354844484695747e-20,  2.8680322412291631e-20,  2.9007196141372126e-20,  2.9335473848423219e-20,
2878                 2.9665163907753988e-20,  2.9996274894828624e-20,  3.0328815589748056e-20,  3.0662794980885287e-20,
2879                 3.0998222268678760e-20,  3.1335106869588609e-20,  3.1673458420220558e-20,  3.2013286781622988e-20,
2880                 3.2354602043762612e-20,  3.2697414530184806e-20,  3.3041734802864950e-20,  3.3387573667257349e-20,
2881                 3.3734942177548938e-20,  3.4083851642125208e-20,  3.4434313629256243e-20,  3.4786339973011376e-20,
2882                 3.5139942779411164e-20,  3.5495134432826171e-20,  3.5851927602632460e-20,  3.6210335250134172e-20,
2883                 3.6570370635764384e-20,  3.6932047326575882e-20,  3.7295379204034252e-20,  3.7660380472126401e-20,
2884                 3.8027065665798284e-20,  3.8395449659736649e-20,  3.8765547677510167e-20,  3.9137375301086406e-20,
2885                 3.9510948480742172e-20,  3.9886283545385430e-20,  4.0263397213308566e-20,  4.0642306603393541e-20,
2886                 4.1023029246790967e-20,  4.1405583099096438e-20,  4.1789986553048817e-20,  4.2176258451776819e-20,
2887                 4.2564418102621759e-20,  4.2954485291566197e-20,  4.3346480298300118e-20,  4.3740423911958146e-20,
2888                 4.4136337447563716e-20,  4.4534242763218286e-20,  4.4934162278076256e-20,  4.5336118991149025e-20,
2889                 4.5740136500984466e-20,  4.6146239026271279e-20,  4.6554451427421133e-20,  4.6964799229185088e-20,
2890                 4.7377308644364938e-20,  4.7792006598684169e-20,  4.8208920756888113e-20,  4.8628079550147814e-20,
2891                 4.9049512204847653e-20,  4.9473248772842596e-20,  4.9899320163277674e-20,  5.0327758176068971e-20,
2892                 5.0758595537153414e-20,  5.1191865935622696e-20,  5.1627604062866059e-20,  5.2065845653856416e-20,
2893                 5.2506627530725194e-20,  5.2949987648783448e-20,  5.3395965145159426e-20,  5.3844600390237576e-20,
2894                 5.4295935042099358e-20,  5.4750012104183868e-20,  5.5206875986405073e-20,  5.5666572569983821e-20,
2895                 5.6129149276275792e-20,  5.6594655139902476e-20,  5.7063140886520563e-20,  5.7534659015596918e-20,
2896                 5.8009263888591218e-20,  5.8487011822987583e-20,  5.8967961192659803e-20,  5.9452172535103471e-20,
2897                 5.9939708666122605e-20,  6.0430634802618929e-20,  6.0925018694200531e-20,  6.1422930764402860e-20,
2898                 6.1924444262401531e-20,  6.2429635426193939e-20,  6.2938583658336214e-20,  6.3451371715447563e-20,
2899                 6.3968085912834963e-20,  6.4488816345752736e-20,  6.5013657128995346e-20,  6.5542706656731714e-20,
2900                 6.6076067884730717e-20,  6.6613848637404196e-20,  6.7156161942412980e-20,  6.7703126395950580e-20,
2901                 6.8254866562246408e-20,  6.8811513411327825e-20,  6.9373204799659681e-20,  6.9940085998959109e-20,
2902                 7.0512310279279503e-20,  7.1090039553397167e-20,  7.1673445090644796e-20,  7.2262708309655784e-20,
2903                 7.2858021661057338e-20,  7.3459589613035800e-20,  7.4067629754967553e-20,  7.4682374037052817e-20,
2904                 7.5304070167226666e-20,  7.5932983190698547e-20,  7.6569397282483754e-20,  7.7213617789487678e-20,
2905                 7.7865973566417016e-20,  7.8526819659456755e-20,  7.9196540403850560e-20,  7.9875553017037968e-20,
2906                 8.0564311788901630e-20,  8.1263312996426176e-20,  8.1973100703706304e-20,  8.2694273652634034e-20,
2907                 8.3427493508836792e-20,  8.4173494807453416e-20,  8.4933097052832066e-20,  8.5707219578230905e-20,
2908                 8.6496899985930695e-20,  8.7303317295655327e-20,  8.8127821378859504e-20,  8.8971970928196666e-20,
2909                 8.9837583239314064e-20,  9.0726800697869543e-20,  9.1642181484063544e-20,  9.2586826406702765e-20,
2910                 9.3564561480278864e-20,  9.4580210012636175e-20,  9.5640015550850358e-20,  9.6752334770503130e-20,
2911                 9.7928851697808831e-20,  9.9186905857531331e-20,  1.0055456271343397e-19,  1.0208407377305566e-19,
2912                 1.0390360993240711e-19,  1.0842021724855044e-19 };
2913 
2914         // alias_threshold[j] is a threshold for the probability mass function that has been
2915         // scaled by (2**64 - 1), translated by -(2**63), and represented as a long value;
2916         // in this way it can be directly compared to a randomly chosen long value.
2917         static final long[] normalAliasThreshold = {    // 256 entries
2918                 9223372036854775732L,  1100243796470199922L,  7866600928967318259L,  6788754710669718688L,
2919                 9022865200207136940L,  6522434035182564354L,  4723064097388367094L,  3360495653202227820L,
2920                 2289663232347306830L,  1423968905585875379L,   708364817795238883L,   106102487338962592L,
2921                 -408333464668584328L,  -853239722790494085L, -1242095211827090004L, -1585059631108655444L,
2922                 -1889943050267333598L, -2162852901996526266L, -2408637386596951353L, -2631196530256993348L,
2923                 -2833704942542501760L, -3018774289008775598L, -3188573753501888049L, -3344920681670389334L,
2924                 -3489349705095933019L, -3623166100045386711L, -3747487436861293578L, -3863276422709141026L,
2925                 -3971367044055496571L, -4072485557008423504L, -4167267476835653997L, -4256271432259158584L,
2926                 -4339990541931699221L, -4418861817116128356L, -4493273980399812066L, -4563574004455583972L,
2927                 -4630072609765608272L, -4693048910437239656L, -4752754358851355990L, -4809416110064308151L,
2928                 -4863239903553549801L, -4914412541525462120L, -4963104028438393907L, -5009469424783376781L,
2929                 -5053650458852410933L, -5095776932714599237L, -5135967952538787362L, -5174333008440005397L,
2930                 -5210972924976812191L, -5245980700089102084L, -5279442247516610920L, -5311437055455710870L,
2931                 -5342038772315685218L, -5371315728848281940L, -5399331404596850615L, -5426144845492958401L,
2932                 -5451811038482575296L, -5476381248268660540L, -5499903320574200237L, -5522421955754019296L,
2933                 -5543978956088644891L, -5564613449670076120L, -5584362093426489951L, -5603259257517942559L,
2934                 -5621337193067953247L, -5638626184957155131L, -5655154691206501482L, -5670949470299055313L,
2935                 -5686035697633988263L, -5700437072176015065L, -5714175914241450413L, -5727273255262198220L,
2936                 -5739748920276454057L, -5751621603817308582L, -5762908939796390234L, -5773627565922293024L,
2937                 -5783793183134813122L, -5793420610488485693L, -5802523835876777512L, -5811116062947540603L,
2938                 -5819209754528321254L, -5826816672847738703L, -5833947916812588598L, -5840613956576464230L,
2939                 -5846824665611918318L, -5852589350480860931L, -5857916778478181241L, -5862815203308620040L,
2940                 -5867292388942958035L, -5871355631785040459L, -5875011781271709877L, -5878267259014830525L,
2941                 -5881128076587168793L, -5883599852042383670L, -5885687825255517495L, -5887396872158140520L,
2942                 -5888731517940791413L, -5889695949285098191L, -5890294025685452079L, -5890529289913339019L,
2943                 -5890404977673728891L, -5889924026498433105L, -5889089083917111413L, -5887902514943630556L,
2944                 -5886366408911444323L, -5884482585689698188L, -5882252601307215732L, -5879677753010810505L,
2945                 -5876759083779777633L, -5873497386319005871L, -5869893206546653493L, -5865946846595933526L,
2946                 -5861658367342436656L, -5857027590471882377L, -5852054100098427498L, -5846737243942430862L,
2947                 -5841076134076202917L, -5835069647242632620L, -5828716424752710909L, -5822014871963881822L,
2948                 -5814963157341321336L, -5807559211102860368L, -5799800723445392235L, -5791685142351319976L,
2949                 -5783209670970726741L, -5774371264573181466L, -5765166627063894671L, -5755592207054728713L,
2950                 -5745644193480823967L, -5735318510752045177L, -5724610813425415465L, -5713516480385581414L,
2951                 -5702030608515423737L, -5690148005840583288L, -5677863184127162093L, -5665170350911168791L,
2952                 -5652063400935782694L, -5638535906971010691L, -5624581109986711207L, -5610191908648783765L,
2953                 -5595360848105231304L, -5580080108024969737L, -5564341489852042876L, -5548136403231016978L,
2954                 -5531455851558564459L, -5514290416611714856L, -5496630242199355791L, -5478465016777918644L,
2955                 -5459783954970839371L, -5440575777921757436L, -5420828692410297267L, -5400530368650229789L,
2956                 -5379667916685479525L, -5358227861290596404L, -5336196115276119372L, -5313557951090901350L,
2957                 -5290297970603367798L, -5266400072934326313L, -5241847420204395031L, -5216622401044877639L,
2958                 -5190706591710560934L, -5164080714616987256L, -5136724594109421094L, -5108617109256031912L,
2959                 -5079736143434386281L, -5050058530465123570L, -5019559997019987907L, -4988215101007960589L,
2960                 -4955997165616088151L, -4922878208649305943L, -4888828866781574127L, -4853818314291958392L,
2961                 -4817814175818125756L, -4780782432613346925L, -4742687321741700014L, -4703491227589533028L,
2962                 -4663154565006030194L, -4621635653315226847L, -4578890580363657638L, -4534873055674290590L,
2963                 -4489534251682380820L, -4442822631912146606L, -4394683764829968681L, -4345060121963632469L,
2964                 -4293890858720706245L, -4241111576152819891L, -4186654061709945180L, -4130446006793453666L,
2965                 -4072410698652140640L, -4012466683862855933L, -3950527400292573339L, -3886500774045756804L,
2966                 -3820288777448438119L, -3751786943603804843L, -3680883832458819395L, -3607460442634330728L,
2967                 -3531389562479403081L, -3452535052892669800L, -3370751053387208615L, -3285881101636362572L,
2968                 -3197757155290696249L, -3106198503163967069L, -3011010550898974052L, -2911983463889090176L,
2969                 -2808890647471134035L, -2701487041141521265L, -2589507199668960785L, -2472663129352313038L,
2970                 -2350641842148622058L, -2223102583752258356L, -2089673683718520949L, -1949948966041670625L,
2971                 -1803483646850545328L, -1649789631543398131L, -1488330106106063370L, -1318513295716695859L,
2972                 -1139685236949889721L,  -951121376566993538L,  -752016768187462359L,  -541474585679321485L,
2973                 -318492605702529265L,   -81947227237782935L,   169425512586600501L,   437052607251310002L,
2974                 722551297576808029L,  1027761939321803391L,  1354787941562529921L,  1706044619231670700L,
2975                 2084319374410687061L,  2492846399585974279L,  2935400169364870493L,  3416413484632185639L,
2976                 3941127949845221101L,  4515787798750242711L,  5147892401460631081L,  5846529325404347588L,
2977                 6622819682189677227L,  7490522659877439279L,  8466869998300400224L,  8216968526327386835L,
2978                 4550693915429835301L,  7628019504075715697L,  6605080500885794707L,  7121156327618549405L,
2979                 2484871780310660533L,  7179104797025802172L,  7066086283790288107L,  1516500120772178463L,
2980                 216305945406470492L,  6295963418490399062L,  2889316805640753770L, -2712587580563247199L,
2981                 6562498853480442900L,  7975754821117214681L, -9223372036854775807L, -9223372036854775807L };
2982 
2983         static final byte[] normalAliasMap = {    // 256 entries
2984                 (byte)  0, (byte)  0, (byte)239, (byte)  2, (byte)  0, (byte)  0, (byte)  0, (byte)  0,
2985                 (byte)  0, (byte)  0, (byte)  0, (byte)  0, (byte)  1, (byte)  1, (byte)  1, (byte)253,
2986                 (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253,
2987                 (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253,
2988                 (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253,
2989                 (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253,
2990                 (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253,
2991                 (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253,
2992                 (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253,
2993                 (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253,
2994                 (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253,
2995                 (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253,
2996                 (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253,
2997                 (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253,
2998                 (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253,
2999                 (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253,
3000                 (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253,
3001                 (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253,
3002                 (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253,
3003                 (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253,
3004                 (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253,
3005                 (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253,
3006                 (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253,
3007                 (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253, (byte)253,
3008                 (byte)253, (byte)253, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252, (byte)252,
3009                 (byte)252, (byte)252, (byte)252, (byte)252, (byte)251, (byte)251, (byte)251, (byte)251,
3010                 (byte)251, (byte)251, (byte)251, (byte)250, (byte)250, (byte)250, (byte)250, (byte)250,
3011                 (byte)249, (byte)249, (byte)249, (byte)248, (byte)248, (byte)248, (byte)247, (byte)247,
3012                 (byte)247, (byte)246, (byte)246, (byte)245, (byte)244, (byte)244, (byte)243, (byte)242,
3013                 (byte)240, (byte)  2, (byte)  2, (byte)  3, (byte)  3, (byte)  0, (byte)  0, (byte)240,
3014                 (byte)241, (byte)242, (byte)243, (byte)244, (byte)245, (byte)246, (byte)247, (byte)248,
3015                 (byte)249, (byte)250, (byte)251, (byte)252, (byte)253, (byte)  1, (byte)  0, (byte)  0 };
3016 
3017     }
3018 
3019 }
3020