Synthia
Generic and flexible data structure generator
Random.java
Go to the documentation of this file.
1 /*
2  * Copyright (c) 1995, 2013, 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 ca.uqac.lif.synthia.random;
27 import java.util.Spliterator;
28 import java.util.concurrent.atomic.AtomicLong;
29 import java.util.function.DoubleConsumer;
30 import java.util.function.IntConsumer;
31 import java.util.function.LongConsumer;
32 import java.util.stream.DoubleStream;
33 import java.util.stream.IntStream;
34 import java.util.stream.LongStream;
35 import java.util.stream.StreamSupport;
36 
37 /**
38  * An instance of this class is used to generate a stream of
39  * pseudorandom numbers. The class uses a 48-bit seed, which is
40  * modified using a linear congruential formula. (See Donald Knuth,
41  * <i>The Art of Computer Programming, Volume 2</i>, Section 3.2.1.)
42  * <p>
43  * If two instances of {@code Random} are created with the same
44  * seed, and the same sequence of method calls is made for each, they
45  * will generate and return identical sequences of numbers. In order to
46  * guarantee this property, particular algorithms are specified for the
47  * class {@code Random}. Java implementations must use all the algorithms
48  * shown here for the class {@code Random}, for the sake of absolute
49  * portability of Java code. However, subclasses of class {@code Random}
50  * are permitted to use other algorithms, so long as they adhere to the
51  * general contracts for all the methods.
52  * <p>
53  * The algorithms implemented by class {@code Random} use a
54  * {@code protected} utility method that on each invocation can supply
55  * up to 32 pseudorandomly generated bits.
56  * <p>
57  * Many applications will find the method {@link Math#random} simpler to use.
58  *
59  * <p>Instances of {@code java.util.Random} are threadsafe.
60  * However, the concurrent use of the same {@code java.util.Random}
61  * instance across threads may encounter contention and consequent
62  * poor performance. Consider instead using
63  * {@link java.util.concurrent.ThreadLocalRandom} in multithreaded
64  * designs.
65  *
66  * <p>Instances of {@code java.util.Random} are not cryptographically
67  * secure. Consider instead using {@link java.security.SecureRandom} to
68  * get a cryptographically secure pseudo-random number generator for use
69  * by security-sensitive applications.
70  *
71  * @author Frank Yellin
72  * @since 1.0
73  * @ingroup API
74  */
75 public class Random {
76  /** use serialVersionUID from JDK 1.1 for interoperability */
77  static final long serialVersionUID = 3905348978240129619L;
78 
79  /**
80  * The internal state associated with this pseudorandom number generator.
81  * (The specs for the methods in this class describe the ongoing
82  * computation of this value.)
83  */
84  private final AtomicLong seed;
85 
86  private static final long multiplier = 0x5DEECE66DL;
87  private static final long addend = 0xBL;
88  private static final long mask = (1L << 48) - 1;
89 
90  private static final double DOUBLE_UNIT = 0x1.0p-53; // 1.0 / (1L << 53)
91 
92  // IllegalArgumentException messages
93  static final String BadBound = "bound must be positive";
94  static final String BadRange = "bound must be greater than origin";
95  static final String BadSize = "size must be non-negative";
96 
97  /**
98  * Creates a new random number generator. This constructor sets
99  * the seed of the random number generator to a value very likely
100  * to be distinct from any other invocation of this constructor.
101  */
102  public Random() {
103  this(seedUniquifier() ^ System.nanoTime());
104  }
105 
106  //TODO complete this doc comment.
107  /**
108  * Private constructor used to create an exact copy of the actual instance of the class.
109  * @param seed The seed of the random generator.
110  * @param nextNextGaussian
111  * @param haveNextNextGaussian
112  */
113  private Random(AtomicLong seed, double nextNextGaussian, boolean haveNextNextGaussian) {
114  this.seed = seed;
115  this.nextNextGaussian = nextNextGaussian;
116  this.haveNextNextGaussian = haveNextNextGaussian;
117  }
118 
119  /**
120  * Creates a new instance of the class with the exact same internal states that the original one.
121  * @return The copy of the actual instance of the class.
122  */
123  public Random Duplicate() {
124  return new Random(new AtomicLong(this.seed.get()), this.nextNextGaussian
125  , this.haveNextNextGaussian);
126  }
127 
128  private static long seedUniquifier() {
129  // L'Ecuyer, "Tables of Linear Congruential Generators of
130  // Different Sizes and Good Lattice Structure", 1999
131  for (;;) {
132  long current = seedUniquifier.get();
133  long next = current * 181783497276652981L;
134  if (seedUniquifier.compareAndSet(current, next))
135  return next;
136  }
137  }
138 
139  private static final AtomicLong seedUniquifier
140  = new AtomicLong(8682522807148012L);
141 
142  /**
143  * Creates a new random number generator using a single {@code long} seed.
144  * The seed is the initial value of the internal state of the pseudorandom
145  * number generator which is maintained by method {@link #next}.
146  *
147  * <p>The invocation {@code new Random(seed)} is equivalent to:
148  * <pre> {@code
149  * Random rnd = new Random();
150  * rnd.setSeed(seed);}</pre>
151  *
152  * @param seed the initial seed
153  * @see #setSeed(long)
154  */
155  public Random(long seed) {
156  if (getClass() == Random.class)
157  this.seed = new AtomicLong(initialScramble(seed));
158  else {
159  // subclass might have overriden setSeed
160  this.seed = new AtomicLong();
161  setSeed(seed);
162  }
163  }
164 
165  private static long initialScramble(long seed) {
166  return (seed ^ multiplier) & mask;
167  }
168 
169  /**
170  * Sets the seed of this random number generator using a single
171  * {@code long} seed. The general contract of {@code setSeed} is
172  * that it alters the state of this random number generator object
173  * so as to be in exactly the same state as if it had just been
174  * created with the argument {@code seed} as a seed. The method
175  * {@code setSeed} is implemented by class {@code Random} by
176  * atomically updating the seed to
177  * <pre>{@code (seed ^ 0x5DEECE66DL) & ((1L << 48) - 1)}</pre>
178  * and clearing the {@code haveNextNextGaussian} flag used by {@link
179  * #nextGaussian}.
180  *
181  * <p>The implementation of {@code setSeed} by class {@code Random}
182  * happens to use only 48 bits of the given seed. In general, however,
183  * an overriding method may use all 64 bits of the {@code long}
184  * argument as a seed value.
185  *
186  * @param seed the initial seed
187  */
188  synchronized public void setSeed(long seed) {
189  this.seed.set(initialScramble(seed));
190  haveNextNextGaussian = false;
191  }
192 
193  /**
194  * Generates the next pseudorandom number. Subclasses should
195  * override this, as this is used by all other methods.
196  *
197  * <p>The general contract of {@code next} is that it returns an
198  * {@code int} value and if the argument {@code bits} is between
199  * {@code 1} and {@code 32} (inclusive), then that many low-order
200  * bits of the returned value will be (approximately) independently
201  * chosen bit values, each of which is (approximately) equally
202  * likely to be {@code 0} or {@code 1}. The method {@code next} is
203  * implemented by class {@code Random} by atomically updating the seed to
204  * <pre>{@code (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1)}</pre>
205  * and returning
206  * <pre>{@code (int)(seed >>> (48 - bits))}.</pre>
207  *
208  * This is a linear congruential pseudorandom number generator, as
209  * defined by D. H. Lehmer and described by Donald E. Knuth in
210  * <i>The Art of Computer Programming,</i> Volume 3:
211  * <i>Seminumerical Algorithms</i>, section 3.2.1.
212  *
213  * @param bits random bits
214  * @return the next pseudorandom value from this random number
215  * generator's sequence
216  * @since 1.1
217  */
218  protected int next(int bits) {
219  long oldseed, nextseed;
220  AtomicLong seed = this.seed;
221  do {
222  oldseed = seed.get();
223  nextseed = (oldseed * multiplier + addend) & mask;
224  } while (!seed.compareAndSet(oldseed, nextseed));
225  return (int)(nextseed >>> (48 - bits));
226  }
227 
228  /**
229  * Generates random bytes and places them into a user-supplied
230  * byte array. The number of random bytes produced is equal to
231  * the length of the byte array.
232  *
233  * <p>The method {@code nextBytes} is implemented by class {@code Random}
234  * as if by:
235  * <pre> {@code
236  * public void nextBytes(byte[] bytes) {
237  * for (int i = 0; i < bytes.length; )
238  * for (int rnd = nextInt(), n = Math.min(bytes.length - i, 4);
239  * n-- > 0; rnd >>= 8)
240  * bytes[i++] = (byte)rnd;
241  * }}</pre>
242  *
243  * @param bytes the byte array to fill with random bytes
244  * @throws NullPointerException if the byte array is null
245  * @since 1.1
246  */
247  public void nextBytes(byte[] bytes) {
248  for (int i = 0, len = bytes.length; i < len; )
249  for (int rnd = nextInt(),
250  n = Math.min(len - i, Integer.SIZE/Byte.SIZE);
251  n-- > 0; rnd >>= Byte.SIZE)
252  bytes[i++] = (byte)rnd;
253  }
254 
255  /**
256  * The form of nextLong used by LongStream Spliterators. If
257  * origin is greater than bound, acts as unbounded form of
258  * nextLong, else as bounded form.
259  *
260  * @param origin the least value, unless greater than bound
261  * @param bound the upper bound (exclusive), must not equal origin
262  * @return a pseudorandom value
263  */
264  final long internalNextLong(long origin, long bound) {
265  long r = nextLong();
266  if (origin < bound) {
267  long n = bound - origin, m = n - 1;
268  if ((n & m) == 0L) // power of two
269  r = (r & m) + origin;
270  else if (n > 0L) { // reject over-represented candidates
271  for (long u = r >>> 1; // ensure nonnegative
272  u + m - (r = u % n) < 0L; // rejection check
273  u = nextLong() >>> 1) // retry
274  ;
275  r += origin;
276  }
277  else { // range not representable as long
278  while (r < origin || r >= bound)
279  r = nextLong();
280  }
281  }
282  return r;
283  }
284 
285  /**
286  * The form of nextInt used by IntStream Spliterators.
287  * For the unbounded case: uses nextInt().
288  * For the bounded case with representable range: uses nextInt(int bound)
289  * For the bounded case with unrepresentable range: uses nextInt()
290  *
291  * @param origin the least value, unless greater than bound
292  * @param bound the upper bound (exclusive), must not equal origin
293  * @return a pseudorandom value
294  */
295  final int internalNextInt(int origin, int bound) {
296  if (origin < bound) {
297  int n = bound - origin;
298  if (n > 0) {
299  return nextInt(n) + origin;
300  }
301  else { // range not representable as int
302  int r;
303  do {
304  r = nextInt();
305  } while (r < origin || r >= bound);
306  return r;
307  }
308  }
309  else {
310  return nextInt();
311  }
312  }
313 
314  /**
315  * The form of nextDouble used by DoubleStream Spliterators.
316  *
317  * @param origin the least value, unless greater than bound
318  * @param bound the upper bound (exclusive), must not equal origin
319  * @return a pseudorandom value
320  */
321  final double internalNextDouble(double origin, double bound) {
322  double r = nextDouble();
323  if (origin < bound) {
324  r = r * (bound - origin) + origin;
325  if (r >= bound) // correct for rounding
326  r = Double.longBitsToDouble(Double.doubleToLongBits(bound) - 1);
327  }
328  return r;
329  }
330 
331  /**
332  * Returns the next pseudorandom, uniformly distributed {@code int}
333  * value from this random number generator's sequence. The general
334  * contract of {@code nextInt} is that one {@code int} value is
335  * pseudorandomly generated and returned. All 2<sup>32</sup> possible
336  * {@code int} values are produced with (approximately) equal probability.
337  *
338  * <p>The method {@code nextInt} is implemented by class {@code Random}
339  * as if by:
340  * <pre> {@code
341  * public int nextInt() {
342  * return next(32);
343  * }}</pre>
344  *
345  * @return the next pseudorandom, uniformly distributed {@code int}
346  * value from this random number generator's sequence
347  */
348  public int nextInt() {
349  return next(32);
350  }
351 
352  /**
353  * Returns a pseudorandom, uniformly distributed {@code int} value
354  * between 0 (inclusive) and the specified value (exclusive), drawn from
355  * this random number generator's sequence. The general contract of
356  * {@code nextInt} is that one {@code int} value in the specified range
357  * is pseudorandomly generated and returned. All {@code bound} possible
358  * {@code int} values are produced with (approximately) equal
359  * probability. The method {@code nextInt(int bound)} is implemented by
360  * class {@code Random} as if by:
361  * <pre> {@code
362  * public int nextInt(int bound) {
363  * if (bound <= 0)
364  * throw new IllegalArgumentException("bound must be positive");
365  *
366  * if ((bound & -bound) == bound) // i.e., bound is a power of 2
367  * return (int)((bound * (long)next(31)) >> 31);
368  *
369  * int bits, val;
370  * do {
371  * bits = next(31);
372  * val = bits % bound;
373  * } while (bits - val + (bound-1) < 0);
374  * return val;
375  * }}</pre>
376  *
377  * <p>The hedge "approximately" is used in the foregoing description only
378  * because the next method is only approximately an unbiased source of
379  * independently chosen bits. If it were a perfect source of randomly
380  * chosen bits, then the algorithm shown would choose {@code int}
381  * values from the stated range with perfect uniformity.
382  * <p>
383  * The algorithm is slightly tricky. It rejects values that would result
384  * in an uneven distribution (due to the fact that 2^31 is not divisible
385  * by n). The probability of a value being rejected depends on n. The
386  * worst case is n=2^30+1, for which the probability of a reject is 1/2,
387  * and the expected number of iterations before the loop terminates is 2.
388  * <p>
389  * The algorithm treats the case where n is a power of two specially: it
390  * returns the correct number of high-order bits from the underlying
391  * pseudo-random number generator. In the absence of special treatment,
392  * the correct number of <i>low-order</i> bits would be returned. Linear
393  * congruential pseudo-random number generators such as the one
394  * implemented by this class are known to have short periods in the
395  * sequence of values of their low-order bits. Thus, this special case
396  * greatly increases the length of the sequence of values returned by
397  * successive calls to this method if n is a small power of two.
398  *
399  * @param bound the upper bound (exclusive). Must be positive.
400  * @return the next pseudorandom, uniformly distributed {@code int}
401  * value between zero (inclusive) and {@code bound} (exclusive)
402  * from this random number generator's sequence
403  * @throws IllegalArgumentException if bound is not positive
404  * @since 1.2
405  */
406  public int nextInt(int bound) {
407  if (bound <= 0)
408  throw new IllegalArgumentException(BadBound);
409 
410  int r = next(31);
411  int m = bound - 1;
412  if ((bound & m) == 0) // i.e., bound is a power of 2
413  r = (int)((bound * (long)r) >> 31);
414  else {
415  for (int u = r;
416  u - (r = u % bound) + m < 0;
417  u = next(31))
418  ;
419  }
420  return r;
421  }
422 
423  /**
424  * Returns the next pseudorandom, uniformly distributed {@code long}
425  * value from this random number generator's sequence. The general
426  * contract of {@code nextLong} is that one {@code long} value is
427  * pseudorandomly generated and returned.
428  *
429  * <p>The method {@code nextLong} is implemented by class {@code Random}
430  * as if by:
431  * <pre> {@code
432  * public long nextLong() {
433  * return ((long)next(32) << 32) + next(32);
434  * }}</pre>
435  *
436  * Because class {@code Random} uses a seed with only 48 bits,
437  * this algorithm will not return all possible {@code long} values.
438  *
439  * @return the next pseudorandom, uniformly distributed {@code long}
440  * value from this random number generator's sequence
441  */
442  public long nextLong() {
443  // it's okay that the bottom word remains signed.
444  return ((long)(next(32)) << 32) + next(32);
445  }
446 
447  /**
448  * Returns the next pseudorandom, uniformly distributed
449  * {@code boolean} value from this random number generator's
450  * sequence. The general contract of {@code nextBoolean} is that one
451  * {@code boolean} value is pseudorandomly generated and returned. The
452  * values {@code true} and {@code false} are produced with
453  * (approximately) equal probability.
454  *
455  * <p>The method {@code nextBoolean} is implemented by class {@code Random}
456  * as if by:
457  * <pre> {@code
458  * public boolean nextBoolean() {
459  * return next(1) != 0;
460  * }}</pre>
461  *
462  * @return the next pseudorandom, uniformly distributed
463  * {@code boolean} value from this random number generator's
464  * sequence
465  * @since 1.2
466  */
467  public boolean nextBoolean() {
468  return next(1) != 0;
469  }
470 
471  /**
472  * Returns the next pseudorandom, uniformly distributed {@code float}
473  * value between {@code 0.0} and {@code 1.0} from this random
474  * number generator's sequence.
475  *
476  * <p>The general contract of {@code nextFloat} is that one
477  * {@code float} value, chosen (approximately) uniformly from the
478  * range {@code 0.0f} (inclusive) to {@code 1.0f} (exclusive), is
479  * pseudorandomly generated and returned. All 2<sup>24</sup> possible
480  * {@code float} values of the form <i>m&nbsp;x&nbsp;</i>2<sup>-24</sup>,
481  * where <i>m</i> is a positive integer less than 2<sup>24</sup>, are
482  * produced with (approximately) equal probability.
483  *
484  * <p>The method {@code nextFloat} is implemented by class {@code Random}
485  * as if by:
486  * <pre> {@code
487  * public float nextFloat() {
488  * return next(24) / ((float)(1 << 24));
489  * }}</pre>
490  *
491  * <p>The hedge "approximately" is used in the foregoing description only
492  * because the next method is only approximately an unbiased source of
493  * independently chosen bits. If it were a perfect source of randomly
494  * chosen bits, then the algorithm shown would choose {@code float}
495  * values from the stated range with perfect uniformity.<p>
496  * [In early versions of Java, the result was incorrectly calculated as:
497  * <pre> {@code
498  * return next(30) / ((float)(1 << 30));}</pre>
499  * This might seem to be equivalent, if not better, but in fact it
500  * introduced a slight nonuniformity because of the bias in the rounding
501  * of floating-point numbers: it was slightly more likely that the
502  * low-order bit of the significand would be 0 than that it would be 1.]
503  *
504  * @return the next pseudorandom, uniformly distributed {@code float}
505  * value between {@code 0.0} and {@code 1.0} from this
506  * random number generator's sequence
507  */
508  public float nextFloat() {
509  return next(24) / ((float)(1 << 24));
510  }
511 
512  /**
513  * Returns the next pseudorandom, uniformly distributed
514  * {@code double} value between {@code 0.0} and
515  * {@code 1.0} from this random number generator's sequence.
516  *
517  * <p>The general contract of {@code nextDouble} is that one
518  * {@code double} value, chosen (approximately) uniformly from the
519  * range {@code 0.0d} (inclusive) to {@code 1.0d} (exclusive), is
520  * pseudorandomly generated and returned.
521  *
522  * <p>The method {@code nextDouble} is implemented by class {@code Random}
523  * as if by:
524  * <pre> {@code
525  * public double nextDouble() {
526  * return (((long)next(26) << 27) + next(27))
527  * / (double)(1L << 53);
528  * }}</pre>
529  *
530  * <p>The hedge "approximately" is used in the foregoing description only
531  * because the {@code next} method is only approximately an unbiased
532  * source of independently chosen bits. If it were a perfect source of
533  * randomly chosen bits, then the algorithm shown would choose
534  * {@code double} values from the stated range with perfect uniformity.
535  * <p>[In early versions of Java, the result was incorrectly calculated as:
536  * <pre> {@code
537  * return (((long)next(27) << 27) + next(27))
538  * / (double)(1L << 54);}</pre>
539  * This might seem to be equivalent, if not better, but in fact it
540  * introduced a large nonuniformity because of the bias in the rounding
541  * of floating-point numbers: it was three times as likely that the
542  * low-order bit of the significand would be 0 than that it would be 1!
543  * This nonuniformity probably doesn't matter much in practice, but we
544  * strive for perfection.]
545  *
546  * @return the next pseudorandom, uniformly distributed {@code double}
547  * value between {@code 0.0} and {@code 1.0} from this
548  * random number generator's sequence
549  * @see Math#random
550  */
551  public double nextDouble() {
552  return (((long)(next(26)) << 27) + next(27)) * DOUBLE_UNIT;
553  }
554 
555  private double nextNextGaussian;
556  private boolean haveNextNextGaussian = false;
557 
558  /**
559  * Returns the next pseudorandom, Gaussian ("normally") distributed
560  * {@code double} value with mean {@code 0.0} and standard
561  * deviation {@code 1.0} from this random number generator's sequence.
562  * <p>
563  * The general contract of {@code nextGaussian} is that one
564  * {@code double} value, chosen from (approximately) the usual
565  * normal distribution with mean {@code 0.0} and standard deviation
566  * {@code 1.0}, is pseudorandomly generated and returned.
567  *
568  * <p>The method {@code nextGaussian} is implemented by class
569  * {@code Random} as if by a threadsafe version of the following:
570  * <pre> {@code
571  * private double nextNextGaussian;
572  * private boolean haveNextNextGaussian = false;
573  *
574  * public double nextGaussian() {
575  * if (haveNextNextGaussian) {
576  * haveNextNextGaussian = false;
577  * return nextNextGaussian;
578  * } else {
579  * double v1, v2, s;
580  * do {
581  * v1 = 2 * nextDouble() - 1; // between -1.0 and 1.0
582  * v2 = 2 * nextDouble() - 1; // between -1.0 and 1.0
583  * s = v1 * v1 + v2 * v2;
584  * } while (s >= 1 || s == 0);
585  * double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s);
586  * nextNextGaussian = v2 * multiplier;
587  * haveNextNextGaussian = true;
588  * return v1 * multiplier;
589  * }
590  * }}</pre>
591  * This uses the <i>polar method</i> of G. E. P. Box, M. E. Muller, and
592  * G. Marsaglia, as described by Donald E. Knuth in <i>The Art of
593  * Computer Programming</i>, Volume 3: <i>Seminumerical Algorithms</i>,
594  * section 3.4.1, subsection C, algorithm P. Note that it generates two
595  * independent values at the cost of only one call to {@code StrictMath.log}
596  * and one call to {@code StrictMath.sqrt}.
597  *
598  * @return the next pseudorandom, Gaussian ("normally") distributed
599  * {@code double} value with mean {@code 0.0} and
600  * standard deviation {@code 1.0} from this random number
601  * generator's sequence
602  */
603  synchronized public double nextGaussian() {
604  // See Knuth, ACP, Section 3.4.1 Algorithm C.
605  if (haveNextNextGaussian) {
606  haveNextNextGaussian = false;
607  return nextNextGaussian;
608  } else {
609  double v1, v2, s;
610  do {
611  v1 = 2 * nextDouble() - 1; // between -1 and 1
612  v2 = 2 * nextDouble() - 1; // between -1 and 1
613  s = v1 * v1 + v2 * v2;
614  } while (s >= 1 || s == 0);
615  double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s);
616  nextNextGaussian = v2 * multiplier;
617  haveNextNextGaussian = true;
618  return v1 * multiplier;
619  }
620  }
621 
622  // stream methods, coded in a way intended to better isolate for
623  // maintenance purposes the small differences across forms.
624 
625  /**
626  * Returns a stream producing the given {@code streamSize} number of
627  * pseudorandom {@code int} values.
628  *
629  * <p>A pseudorandom {@code int} value is generated as if it's the result of
630  * calling the method {@link #nextInt()}.
631  *
632  * @param streamSize the number of values to generate
633  * @return a stream of pseudorandom {@code int} values
634  * @throws IllegalArgumentException if {@code streamSize} is
635  * less than zero
636  * @since 1.8
637  */
638  public IntStream ints(long streamSize) {
639  if (streamSize < 0L)
640  throw new IllegalArgumentException(BadSize);
641  return StreamSupport.intStream
642  (new RandomIntsSpliterator
643  (this, 0L, streamSize, Integer.MAX_VALUE, 0),
644  false);
645  }
646 
647  /**
648  * Returns an effectively unlimited stream of pseudorandom {@code int}
649  * values.
650  *
651  * <p>A pseudorandom {@code int} value is generated as if it's the result of
652  * calling the method {@link #nextInt()}.
653  *
654  * @implNote This method is implemented to be equivalent to {@code
655  * ints(Long.MAX_VALUE)}.
656  *
657  * @return a stream of pseudorandom {@code int} values
658  * @since 1.8
659  */
660  public IntStream ints() {
661  return StreamSupport.intStream
662  (new RandomIntsSpliterator
663  (this, 0L, Long.MAX_VALUE, Integer.MAX_VALUE, 0),
664  false);
665  }
666 
667  /**
668  * Returns a stream producing the given {@code streamSize} number
669  * of pseudorandom {@code int} values, each conforming to the given
670  * origin (inclusive) and bound (exclusive).
671  *
672  * <p>A pseudorandom {@code int} value is generated as if it's the result of
673  * calling the following method with the origin and bound:
674  * <pre> {@code
675  * int nextInt(int origin, int bound) {
676  * int n = bound - origin;
677  * if (n > 0) {
678  * return nextInt(n) + origin;
679  * }
680  * else { // range not representable as int
681  * int r;
682  * do {
683  * r = nextInt();
684  * } while (r < origin || r >= bound);
685  * return r;
686  * }
687  * }}</pre>
688  *
689  * @param streamSize the number of values to generate
690  * @param randomNumberOrigin the origin (inclusive) of each random value
691  * @param randomNumberBound the bound (exclusive) of each random value
692  * @return a stream of pseudorandom {@code int} values,
693  * each with the given origin (inclusive) and bound (exclusive)
694  * @throws IllegalArgumentException if {@code streamSize} is
695  * less than zero, or {@code randomNumberOrigin}
696  * is greater than or equal to {@code randomNumberBound}
697  * @since 1.8
698  */
699  public IntStream ints(long streamSize, int randomNumberOrigin,
700  int randomNumberBound) {
701  if (streamSize < 0L)
702  throw new IllegalArgumentException(BadSize);
703  if (randomNumberOrigin >= randomNumberBound)
704  throw new IllegalArgumentException(BadRange);
705  return StreamSupport.intStream
706  (new RandomIntsSpliterator
707  (this, 0L, streamSize, randomNumberOrigin, randomNumberBound),
708  false);
709  }
710 
711  /**
712  * Returns an effectively unlimited stream of pseudorandom {@code
713  * int} values, each conforming to the given origin (inclusive) and bound
714  * (exclusive).
715  *
716  * <p>A pseudorandom {@code int} value is generated as if it's the result of
717  * calling the following method with the origin and bound:
718  * <pre> {@code
719  * int nextInt(int origin, int bound) {
720  * int n = bound - origin;
721  * if (n > 0) {
722  * return nextInt(n) + origin;
723  * }
724  * else { // range not representable as int
725  * int r;
726  * do {
727  * r = nextInt();
728  * } while (r < origin || r >= bound);
729  * return r;
730  * }
731  * }}</pre>
732  *
733  * @implNote This method is implemented to be equivalent to {@code
734  * ints(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
735  *
736  * @param randomNumberOrigin the origin (inclusive) of each random value
737  * @param randomNumberBound the bound (exclusive) of each random value
738  * @return a stream of pseudorandom {@code int} values,
739  * each with the given origin (inclusive) and bound (exclusive)
740  * @throws IllegalArgumentException if {@code randomNumberOrigin}
741  * is greater than or equal to {@code randomNumberBound}
742  * @since 1.8
743  */
744  public IntStream ints(int randomNumberOrigin, int randomNumberBound) {
745  if (randomNumberOrigin >= randomNumberBound)
746  throw new IllegalArgumentException(BadRange);
747  return StreamSupport.intStream
748  (new RandomIntsSpliterator
749  (this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
750  false);
751  }
752 
753  /**
754  * Returns a stream producing the given {@code streamSize} number of
755  * pseudorandom {@code long} values.
756  *
757  * <p>A pseudorandom {@code long} value is generated as if it's the result
758  * of calling the method {@link #nextLong()}.
759  *
760  * @param streamSize the number of values to generate
761  * @return a stream of pseudorandom {@code long} values
762  * @throws IllegalArgumentException if {@code streamSize} is
763  * less than zero
764  * @since 1.8
765  */
766  public LongStream longs(long streamSize) {
767  if (streamSize < 0L)
768  throw new IllegalArgumentException(BadSize);
769  return StreamSupport.longStream
770  (new RandomLongsSpliterator
771  (this, 0L, streamSize, Long.MAX_VALUE, 0L),
772  false);
773  }
774 
775  /**
776  * Returns an effectively unlimited stream of pseudorandom {@code long}
777  * values.
778  *
779  * <p>A pseudorandom {@code long} value is generated as if it's the result
780  * of calling the method {@link #nextLong()}.
781  *
782  * @implNote This method is implemented to be equivalent to {@code
783  * longs(Long.MAX_VALUE)}.
784  *
785  * @return a stream of pseudorandom {@code long} values
786  * @since 1.8
787  */
788  public LongStream longs() {
789  return StreamSupport.longStream
790  (new RandomLongsSpliterator
791  (this, 0L, Long.MAX_VALUE, Long.MAX_VALUE, 0L),
792  false);
793  }
794 
795  /**
796  * Returns a stream producing the given {@code streamSize} number of
797  * pseudorandom {@code long}, each conforming to the given origin
798  * (inclusive) and bound (exclusive).
799  *
800  * <p>A pseudorandom {@code long} value is generated as if it's the result
801  * of calling the following method with the origin and bound:
802  * <pre> {@code
803  * long nextLong(long origin, long bound) {
804  * long r = nextLong();
805  * long n = bound - origin, m = n - 1;
806  * if ((n & m) == 0L) // power of two
807  * r = (r & m) + origin;
808  * else if (n > 0L) { // reject over-represented candidates
809  * for (long u = r >>> 1; // ensure nonnegative
810  * u + m - (r = u % n) < 0L; // rejection check
811  * u = nextLong() >>> 1) // retry
812  * ;
813  * r += origin;
814  * }
815  * else { // range not representable as long
816  * while (r < origin || r >= bound)
817  * r = nextLong();
818  * }
819  * return r;
820  * }}</pre>
821  *
822  * @param streamSize the number of values to generate
823  * @param randomNumberOrigin the origin (inclusive) of each random value
824  * @param randomNumberBound the bound (exclusive) of each random value
825  * @return a stream of pseudorandom {@code long} values,
826  * each with the given origin (inclusive) and bound (exclusive)
827  * @throws IllegalArgumentException if {@code streamSize} is
828  * less than zero, or {@code randomNumberOrigin}
829  * is greater than or equal to {@code randomNumberBound}
830  * @since 1.8
831  */
832  public LongStream longs(long streamSize, long randomNumberOrigin,
833  long randomNumberBound) {
834  if (streamSize < 0L)
835  throw new IllegalArgumentException(BadSize);
836  if (randomNumberOrigin >= randomNumberBound)
837  throw new IllegalArgumentException(BadRange);
838  return StreamSupport.longStream
839  (new RandomLongsSpliterator
840  (this, 0L, streamSize, randomNumberOrigin, randomNumberBound),
841  false);
842  }
843 
844  /**
845  * Returns an effectively unlimited stream of pseudorandom {@code
846  * long} values, each conforming to the given origin (inclusive) and bound
847  * (exclusive).
848  *
849  * <p>A pseudorandom {@code long} value is generated as if it's the result
850  * of calling the following method with the origin and bound:
851  * <pre> {@code
852  * long nextLong(long origin, long bound) {
853  * long r = nextLong();
854  * long n = bound - origin, m = n - 1;
855  * if ((n & m) == 0L) // power of two
856  * r = (r & m) + origin;
857  * else if (n > 0L) { // reject over-represented candidates
858  * for (long u = r >>> 1; // ensure nonnegative
859  * u + m - (r = u % n) < 0L; // rejection check
860  * u = nextLong() >>> 1) // retry
861  * ;
862  * r += origin;
863  * }
864  * else { // range not representable as long
865  * while (r < origin || r >= bound)
866  * r = nextLong();
867  * }
868  * return r;
869  * }}</pre>
870  *
871  * @implNote This method is implemented to be equivalent to {@code
872  * longs(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
873  *
874  * @param randomNumberOrigin the origin (inclusive) of each random value
875  * @param randomNumberBound the bound (exclusive) of each random value
876  * @return a stream of pseudorandom {@code long} values,
877  * each with the given origin (inclusive) and bound (exclusive)
878  * @throws IllegalArgumentException if {@code randomNumberOrigin}
879  * is greater than or equal to {@code randomNumberBound}
880  * @since 1.8
881  */
882  public LongStream longs(long randomNumberOrigin, long randomNumberBound) {
883  if (randomNumberOrigin >= randomNumberBound)
884  throw new IllegalArgumentException(BadRange);
885  return StreamSupport.longStream
886  (new RandomLongsSpliterator
887  (this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
888  false);
889  }
890 
891  /**
892  * Returns a stream producing the given {@code streamSize} number of
893  * pseudorandom {@code double} values, each between zero
894  * (inclusive) and one (exclusive).
895  *
896  * <p>A pseudorandom {@code double} value is generated as if it's the result
897  * of calling the method {@link #nextDouble()}}.
898  *
899  * @param streamSize the number of values to generate
900  * @return a stream of {@code double} values
901  * @throws IllegalArgumentException if {@code streamSize} is
902  * less than zero
903  * @since 1.8
904  */
905  public DoubleStream doubles(long streamSize) {
906  if (streamSize < 0L)
907  throw new IllegalArgumentException(BadSize);
908  return StreamSupport.doubleStream
909  (new RandomDoublesSpliterator
910  (this, 0L, streamSize, Double.MAX_VALUE, 0.0),
911  false);
912  }
913 
914  /**
915  * Returns an effectively unlimited stream of pseudorandom {@code
916  * double} values, each between zero (inclusive) and one
917  * (exclusive).
918  *
919  * <p>A pseudorandom {@code double} value is generated as if it's the result
920  * of calling the method {@link #nextDouble()}}.
921  *
922  * @implNote This method is implemented to be equivalent to {@code
923  * doubles(Long.MAX_VALUE)}.
924  *
925  * @return a stream of pseudorandom {@code double} values
926  * @since 1.8
927  */
928  public DoubleStream doubles() {
929  return StreamSupport.doubleStream
930  (new RandomDoublesSpliterator
931  (this, 0L, Long.MAX_VALUE, Double.MAX_VALUE, 0.0),
932  false);
933  }
934 
935  /**
936  * Returns a stream producing the given {@code streamSize} number of
937  * pseudorandom {@code double} values, each conforming to the given origin
938  * (inclusive) and bound (exclusive).
939  *
940  * <p>A pseudorandom {@code double} value is generated as if it's the result
941  * of calling the following method with the origin and bound:
942  * <pre> {@code
943  * double nextDouble(double origin, double bound) {
944  * double r = nextDouble();
945  * r = r * (bound - origin) + origin;
946  * if (r >= bound) // correct for rounding
947  * r = Math.nextDown(bound);
948  * return r;
949  * }}</pre>
950  *
951  * @param streamSize the number of values to generate
952  * @param randomNumberOrigin the origin (inclusive) of each random value
953  * @param randomNumberBound the bound (exclusive) of each random value
954  * @return a stream of pseudorandom {@code double} values,
955  * each with the given origin (inclusive) and bound (exclusive)
956  * @throws IllegalArgumentException if {@code streamSize} is
957  * less than zero
958  * @throws IllegalArgumentException if {@code randomNumberOrigin}
959  * is greater than or equal to {@code randomNumberBound}
960  * @since 1.8
961  */
962  public DoubleStream doubles(long streamSize, double randomNumberOrigin,
963  double randomNumberBound) {
964  if (streamSize < 0L)
965  throw new IllegalArgumentException(BadSize);
966  if (!(randomNumberOrigin < randomNumberBound))
967  throw new IllegalArgumentException(BadRange);
968  return StreamSupport.doubleStream
969  (new RandomDoublesSpliterator
970  (this, 0L, streamSize, randomNumberOrigin, randomNumberBound),
971  false);
972  }
973 
974  /**
975  * Returns an effectively unlimited stream of pseudorandom {@code
976  * double} values, each conforming to the given origin (inclusive) and bound
977  * (exclusive).
978  *
979  * <p>A pseudorandom {@code double} value is generated as if it's the result
980  * of calling the following method with the origin and bound:
981  * <pre> {@code
982  * double nextDouble(double origin, double bound) {
983  * double r = nextDouble();
984  * r = r * (bound - origin) + origin;
985  * if (r >= bound) // correct for rounding
986  * r = Math.nextDown(bound);
987  * return r;
988  * }}</pre>
989  *
990  * @implNote This method is implemented to be equivalent to {@code
991  * doubles(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound)}.
992  *
993  * @param randomNumberOrigin the origin (inclusive) of each random value
994  * @param randomNumberBound the bound (exclusive) of each random value
995  * @return a stream of pseudorandom {@code double} values,
996  * each with the given origin (inclusive) and bound (exclusive)
997  * @throws IllegalArgumentException if {@code randomNumberOrigin}
998  * is greater than or equal to {@code randomNumberBound}
999  * @since 1.8
1000  */
1001  public DoubleStream doubles(double randomNumberOrigin, double randomNumberBound) {
1002  if (!(randomNumberOrigin < randomNumberBound))
1003  throw new IllegalArgumentException(BadRange);
1004  return StreamSupport.doubleStream
1005  (new RandomDoublesSpliterator
1006  (this, 0L, Long.MAX_VALUE, randomNumberOrigin, randomNumberBound),
1007  false);
1008  }
1009 
1010  /**
1011  * Spliterator for int streams. We multiplex the four int
1012  * versions into one class by treating a bound less than origin as
1013  * unbounded, and also by treating "infinite" as equivalent to
1014  * Long.MAX_VALUE. For splits, it uses the standard divide-by-two
1015  * approach. The long and double versions of this class are
1016  * identical except for types.
1017  */
1018  static final class RandomIntsSpliterator implements Spliterator.OfInt {
1019  final Random rng;
1020  long index;
1021  final long fence;
1022  final int origin;
1023  final int bound;
1024  RandomIntsSpliterator(Random rng, long index, long fence,
1025  int origin, int bound) {
1026  this.rng = rng; this.index = index; this.fence = fence;
1027  this.origin = origin; this.bound = bound;
1028  }
1029 
1030  public RandomIntsSpliterator trySplit() {
1031  long i = index, m = (i + fence) >>> 1;
1032  return (m <= i) ? null :
1033  new RandomIntsSpliterator(rng, i, index = m, origin, bound);
1034  }
1035 
1036  public long estimateSize() {
1037  return fence - index;
1038  }
1039 
1040  public int characteristics() {
1041  return (Spliterator.SIZED | Spliterator.SUBSIZED |
1042  Spliterator.NONNULL | Spliterator.IMMUTABLE);
1043  }
1044 
1045  public boolean tryAdvance(IntConsumer consumer) {
1046  if (consumer == null) throw new NullPointerException();
1047  long i = index, f = fence;
1048  if (i < f) {
1049  consumer.accept(rng.internalNextInt(origin, bound));
1050  index = i + 1;
1051  return true;
1052  }
1053  return false;
1054  }
1055 
1056  public void forEachRemaining(IntConsumer consumer) {
1057  if (consumer == null) throw new NullPointerException();
1058  long i = index, f = fence;
1059  if (i < f) {
1060  index = f;
1061  Random r = rng;
1062  int o = origin, b = bound;
1063  do {
1064  consumer.accept(r.internalNextInt(o, b));
1065  } while (++i < f);
1066  }
1067  }
1068  }
1069 
1070  /**
1071  * Spliterator for long streams.
1072  */
1073  static final class RandomLongsSpliterator implements Spliterator.OfLong {
1074  final Random rng;
1075  long index;
1076  final long fence;
1077  final long origin;
1078  final long bound;
1079  RandomLongsSpliterator(Random rng, long index, long fence,
1080  long origin, long bound) {
1081  this.rng = rng; this.index = index; this.fence = fence;
1082  this.origin = origin; this.bound = bound;
1083  }
1084 
1085  public RandomLongsSpliterator trySplit() {
1086  long i = index, m = (i + fence) >>> 1;
1087  return (m <= i) ? null :
1088  new RandomLongsSpliterator(rng, i, index = m, origin, bound);
1089  }
1090 
1091  public long estimateSize() {
1092  return fence - index;
1093  }
1094 
1095  public int characteristics() {
1096  return (Spliterator.SIZED | Spliterator.SUBSIZED |
1097  Spliterator.NONNULL | Spliterator.IMMUTABLE);
1098  }
1099 
1100  public boolean tryAdvance(LongConsumer consumer) {
1101  if (consumer == null) throw new NullPointerException();
1102  long i = index, f = fence;
1103  if (i < f) {
1104  consumer.accept(rng.internalNextLong(origin, bound));
1105  index = i + 1;
1106  return true;
1107  }
1108  return false;
1109  }
1110 
1111  public void forEachRemaining(LongConsumer consumer) {
1112  if (consumer == null) throw new NullPointerException();
1113  long i = index, f = fence;
1114  if (i < f) {
1115  index = f;
1116  Random r = rng;
1117  long o = origin, b = bound;
1118  do {
1119  consumer.accept(r.internalNextLong(o, b));
1120  } while (++i < f);
1121  }
1122  }
1123 
1124  }
1125 
1126  /**
1127  * Spliterator for double streams.
1128  */
1129  static final class RandomDoublesSpliterator implements Spliterator.OfDouble {
1130  final Random rng;
1131  long index;
1132  final long fence;
1133  final double origin;
1134  final double bound;
1135  RandomDoublesSpliterator(Random rng, long index, long fence,
1136  double origin, double bound) {
1137  this.rng = rng; this.index = index; this.fence = fence;
1138  this.origin = origin; this.bound = bound;
1139  }
1140 
1141  public RandomDoublesSpliterator trySplit() {
1142  long i = index, m = (i + fence) >>> 1;
1143  return (m <= i) ? null :
1144  new RandomDoublesSpliterator(rng, i, index = m, origin, bound);
1145  }
1146 
1147  public long estimateSize() {
1148  return fence - index;
1149  }
1150 
1151  public int characteristics() {
1152  return (Spliterator.SIZED | Spliterator.SUBSIZED |
1153  Spliterator.NONNULL | Spliterator.IMMUTABLE);
1154  }
1155 
1156  public boolean tryAdvance(DoubleConsumer consumer) {
1157  if (consumer == null) throw new NullPointerException();
1158  long i = index, f = fence;
1159  if (i < f) {
1160  consumer.accept(rng.internalNextDouble(origin, bound));
1161  index = i + 1;
1162  return true;
1163  }
1164  return false;
1165  }
1166 
1167  public void forEachRemaining(DoubleConsumer consumer) {
1168  if (consumer == null) throw new NullPointerException();
1169  long i = index, f = fence;
1170  if (i < f) {
1171  index = f;
1172  Random r = rng;
1173  double o = origin, b = bound;
1174  do {
1175  consumer.accept(r.internalNextDouble(o, b));
1176  } while (++i < f);
1177  }
1178  }
1179  }
1180 }
ca.uqac.lif.synthia.random.Random.nextDouble
double nextDouble()
Returns the next pseudorandom, uniformly distributed.
Definition: Random.java:551
ca.uqac.lif.synthia.random.Random.ints
IntStream ints(long streamSize, int randomNumberOrigin, int randomNumberBound)
Returns a stream producing the given.
Definition: Random.java:699
ca.uqac.lif.synthia.random.Random.setSeed
synchronized void setSeed(long seed)
Sets the seed of this random number generator using a single.
Definition: Random.java:188
ca.uqac.lif.synthia.random.Random.doubles
DoubleStream doubles(long streamSize, double randomNumberOrigin, double randomNumberBound)
Returns a stream producing the given.
Definition: Random.java:962
ca.uqac.lif.synthia.random.Random.next
int next(int bits)
Generates the next pseudorandom number.
Definition: Random.java:218
ca.uqac.lif.synthia.random.Random.ints
IntStream ints(int randomNumberOrigin, int randomNumberBound)
Returns an effectively unlimited stream of pseudorandom.
Definition: Random.java:744
ca.uqac.lif.synthia.random.Random.longs
LongStream longs(long randomNumberOrigin, long randomNumberBound)
Returns an effectively unlimited stream of pseudorandom.
Definition: Random.java:882
ca.uqac.lif.synthia.random.Random.doubles
DoubleStream doubles(long streamSize)
Returns a stream producing the given.
Definition: Random.java:905
ca.uqac.lif.synthia.random.Random.nextInt
int nextInt(int bound)
Returns a pseudorandom, uniformly distributed.
Definition: Random.java:406
ca.uqac.lif.synthia.random.Random.longs
LongStream longs(long streamSize, long randomNumberOrigin, long randomNumberBound)
Returns a stream producing the given.
Definition: Random.java:832
ca.uqac.lif.synthia.random.Random.nextBytes
void nextBytes(byte[] bytes)
Generates random bytes and places them into a user-supplied byte array.
Definition: Random.java:247
ca.uqac.lif.synthia.random.Random.ints
IntStream ints(long streamSize)
Returns a stream producing the given.
Definition: Random.java:638
ca.uqac.lif.synthia.random.Random.longs
LongStream longs()
Returns an effectively unlimited stream of pseudorandom.
Definition: Random.java:788
ca.uqac.lif.synthia.random.Random.nextInt
int nextInt()
Returns the next pseudorandom, uniformly distributed.
Definition: Random.java:348
ca.uqac.lif.synthia.random.Random.nextGaussian
synchronized double nextGaussian()
Returns the next pseudorandom, Gaussian ("normally") distributed.
Definition: Random.java:603
ca.uqac.lif.synthia.random.Random.Duplicate
Random Duplicate()
Creates a new instance of the class with the exact same internal states that the original one.
Definition: Random.java:123
ca.uqac.lif.synthia.random.Random
An instance of this class is used to generate a stream of pseudorandom numbers.
Definition: Random.java:75
ca.uqac.lif.synthia.random.Random.doubles
DoubleStream doubles()
Returns an effectively unlimited stream of pseudorandom.
Definition: Random.java:928
ca.uqac.lif.synthia.random.Random.doubles
DoubleStream doubles(double randomNumberOrigin, double randomNumberBound)
Returns an effectively unlimited stream of pseudorandom.
Definition: Random.java:1001
ca.uqac.lif.synthia.random.Random.Random
Random()
Creates a new random number generator.
Definition: Random.java:102
ca.uqac.lif.synthia.random.Random.ints
IntStream ints()
Returns an effectively unlimited stream of pseudorandom.
Definition: Random.java:660
ca.uqac.lif.synthia.random.Random.nextFloat
float nextFloat()
Returns the next pseudorandom, uniformly distributed.
Definition: Random.java:508
ca.uqac.lif.synthia.random.Random.longs
LongStream longs(long streamSize)
Returns a stream producing the given.
Definition: Random.java:766
ca.uqac.lif.synthia.random.Random.nextLong
long nextLong()
Returns the next pseudorandom, uniformly distributed.
Definition: Random.java:442
ca.uqac.lif.synthia.random.Random.nextBoolean
boolean nextBoolean()
Returns the next pseudorandom, uniformly distributed.
Definition: Random.java:467
ca.uqac.lif.synthia.random.Random.Random
Random(long seed)
Creates a new random number generator using a single.
Definition: Random.java:155