1 /* 2 * Copyright (c) 2021, 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 java.util.random; 27 28 import java.math.BigInteger; 29 import java.security.SecureRandom; 30 import java.util.Objects; 31 import java.util.concurrent.ThreadLocalRandom; 32 import jdk.internal.util.random.RandomSupport; 33 import jdk.internal.util.random.RandomSupport.*; 34 35 import java.util.stream.DoubleStream; 36 import java.util.stream.IntStream; 37 import java.util.stream.LongStream; 38 import java.util.stream.Stream; 39 40 /** 41 * The {@link RandomGenerator} interface is designed to provide a common 42 * protocol for objects that generate random or (more typically) pseudorandom 43 * sequences of numbers (or Boolean values). Such a sequence may be obtained by 44 * either repeatedly invoking a method that returns a single pseudorandomly 45 * chosen value, or by invoking a method that returns a stream of 46 * pseudorandomly chosen values. 47 * 48 * <p> Ideally, given an implicitly or explicitly specified range of values, 49 * each value would be chosen independently and uniformly from that range. In 50 * practice, one may have to settle for some approximation to independence and 51 * uniformity. 52 * 53 * <p> In the case of {@code int}, {@code long}, and {@code boolean} values, if 54 * there is no explicit specification of range, then the range includes all 55 * possible values of the type. In the case of {@code float} and {@code double} 56 * values, first a value is always chosen uniformly from the set of 57 * 2<sup><i>w</i></sup> values between 0.0 (inclusive) and 1.0 (exclusive), 58 * where <i>w</i> is 23 for {@code float} values and 52 for {@code double} 59 * values, such that adjacent values differ by 2<sup>−<i>w</i></sup> 60 * (notice that this set is a <i>subset</i> of the set of 61 * <i>all representable floating-point values</i> between 0.0 (inclusive) and 1.0 (exclusive)); 62 * then if an explicit range was specified, then the chosen number is 63 * computationally scaled and translated so as to appear to have been chosen 64 * approximately uniformly from that explicit range. 65 * 66 * <p> Each method that returns a stream produces a stream of values each of 67 * which is chosen in the same manner as for a method that returns a single 68 * pseudorandomly chosen value. For example, if {@code r} implements 69 * {@link RandomGenerator}, then the method call {@code r.ints(100)} returns a 70 * stream of 100 {@code int} values. These are not necessarily the exact same 71 * values that would have been returned if instead {@code r.nextInt()} had been 72 * called 100 times; all that is guaranteed is that each value in the stream is 73 * chosen in a similar pseudorandom manner from the same range. 74 * 75 * <p> Every object that implements the {@link RandomGenerator} interface by 76 * using a pseudorandom algorithm is assumed to contain a finite amount of 77 * state. Using such an object to generate a pseudorandomly chosen value alters 78 * its state by computing a new state as a function of the current state, 79 * without reference to any information other than the current state. The number 80 * of distinct possible states of such an object is called its <i>period</i>. 81 * (Some implementations of the {@link RandomGenerator} interface may be truly 82 * random rather than pseudorandom, for example relying on the statistical 83 * behavior of a physical object to derive chosen values. Such implementations 84 * do not have a fixed period.) 85 * 86 * <p> As a rule, objects that implement the {@link RandomGenerator} interface 87 * need not be thread-safe. It is recommended that multithreaded applications 88 * use either {@link ThreadLocalRandom} or (preferably) pseudorandom number 89 * generators that implement the {@link SplittableGenerator} or 90 * {@link JumpableGenerator} interface. 91 * 92 * <p> Objects that implement {@link RandomGenerator} are typically not 93 * cryptographically secure. Consider instead using {@link SecureRandom} to get 94 * a cryptographically secure pseudorandom number generator for use by 95 * security-sensitive applications. Note, however, that {@link SecureRandom} 96 * does implement the {@link RandomGenerator} interface, so that instances of 97 * {@link SecureRandom} may be used interchangeably with other types of 98 * pseudorandom generators in applications that do not require a secure 99 * generator. 100 * 101 * <p>Unless explicit stated otherwise, the use of null for any method argument 102 * will cause a NullPointerException. 103 * 104 * @since 17 105 * 106 */ 107 public interface RandomGenerator { 108 /** 109 * Returns an instance of {@link RandomGenerator} that utilizes the 110 * {@code name} <a href="package-summary.html#algorithms">algorithm</a>. 111 * 112 * @param name Name of random number generator 113 * <a href="package-summary.html#algorithms">algorithm</a> 114 * 115 * @return An instance of {@link RandomGenerator} 116 * 117 * @throws NullPointerException if name is null 118 * @throws IllegalArgumentException if the named algorithm is not found 119 */ of(String name)120 static RandomGenerator of(String name) { 121 Objects.requireNonNull(name); 122 123 return RandomGeneratorFactory.of(name, RandomGenerator.class); 124 } 125 126 /** 127 * Returns a {@link RandomGenerator} meeting the minimal requirement 128 * of having an <a href="package-summary.html#algorithms">algorithm</a> 129 * whose state bits are greater than or equal 64. 130 * 131 * @implSpec Since algorithms will improve over time, there is no 132 * guarantee that this method will return the same algorithm over time. 133 * <p> The default implementation selects L32X64MixRandom. 134 * 135 * @return a {@link RandomGenerator} 136 */ getDefault()137 static RandomGenerator getDefault() { 138 return of("L32X64MixRandom"); 139 } 140 141 /** 142 * Return true if the implementation of RandomGenerator (algorithm) has been 143 * marked for deprecation. 144 * 145 * @implNote Random number generator algorithms evolve over time; new 146 * algorithms will be introduced and old algorithms will 147 * lose standing. If an older algorithm is deemed unsuitable 148 * for continued use, it will be marked as deprecated to indicate 149 * that it may be removed at some point in the future. 150 * 151 * @return true if the implementation of RandomGenerator (algorithm) has been 152 * marked for deprecation 153 * 154 * @implSpec The default implementation checks for the @Deprecated annotation. 155 */ isDeprecated()156 default boolean isDeprecated() { 157 return this.getClass().isAnnotationPresent(Deprecated.class); 158 } 159 160 /** 161 * Returns an effectively unlimited stream of pseudorandomly chosen 162 * {@code double} values. 163 * 164 * @return a stream of pseudorandomly chosen {@code double} values 165 * 166 * @implNote It is permitted to implement this method in a manner equivalent to 167 * {@link RandomGenerator#doubles(long) doubles} 168 * ({@link Long#MAX_VALUE Long.MAX_VALUE}). 169 * 170 * @implSpec The default implementation produces a sequential stream 171 * that repeatedly calls {@link RandomGenerator#nextDouble nextDouble}(). 172 */ doubles()173 default DoubleStream doubles() { 174 return DoubleStream.generate(this::nextDouble).sequential(); 175 } 176 177 /** 178 * Returns an effectively unlimited stream of pseudorandomly chosen 179 * {@code double} values, where each value is between the specified origin 180 * (inclusive) and the specified bound (exclusive). 181 * 182 * @param randomNumberOrigin the least value that can be produced 183 * @param randomNumberBound the upper bound (exclusive) for each value produced 184 * 185 * @return a stream of pseudorandomly chosen {@code double} values, each between 186 * the specified origin (inclusive) and the specified bound (exclusive) 187 * 188 * @throws IllegalArgumentException if {@code randomNumberOrigin} is not finite, 189 * or {@code randomNumberBound} is not finite, or {@code randomNumberOrigin} 190 * is greater than or equal to {@code randomNumberBound} 191 * 192 * @implNote It is permitted to implement this method in a manner equivalent to 193 * {@link RandomGenerator#doubles(long, double, double) doubles} 194 * ({@link Long#MAX_VALUE Long.MAX_VALUE}, randomNumberOrigin, randomNumberBound). 195 * 196 * @implSpec The default implementation produces a sequential stream that repeatedly 197 * calls {@link RandomGenerator#nextDouble(double, double) nextDouble}(randomNumberOrigin, randomNumberBound). 198 */ doubles(double randomNumberOrigin, double randomNumberBound)199 default DoubleStream doubles(double randomNumberOrigin, double randomNumberBound) { 200 RandomSupport.checkRange(randomNumberOrigin, randomNumberBound); 201 202 return DoubleStream.generate(() -> nextDouble(randomNumberOrigin, randomNumberBound)).sequential(); 203 } 204 205 /** 206 * Returns a stream producing the given {@code streamSize} number of 207 * pseudorandomly chosen {@code double} values. 208 * 209 * @param streamSize the number of values to generate 210 * 211 * @return a stream of pseudorandomly chosen {@code double} values 212 * 213 * @throws IllegalArgumentException if {@code streamSize} is 214 * less than zero 215 * 216 * @implSpec The default implementation produces a sequential stream 217 * that repeatedly calls {@link RandomGenerator#nextDouble nextDouble()}. 218 */ doubles(long streamSize)219 default DoubleStream doubles(long streamSize) { 220 RandomSupport.checkStreamSize(streamSize); 221 222 return doubles().limit(streamSize); 223 } 224 225 /** 226 * Returns a stream producing the given {@code streamSize} number of 227 * pseudorandomly chosen {@code double} values, where each value is 228 * between the specified origin (inclusive) and the specified bound 229 * (exclusive). 230 * 231 * @param streamSize the number of values to generate 232 * @param randomNumberOrigin the least value that can be produced 233 * @param randomNumberBound the upper bound (exclusive) for each value produced 234 * 235 * @return a stream of pseudorandomly chosen {@code double} values, each between 236 * the specified origin (inclusive) and the specified bound (exclusive) 237 * 238 * @throws IllegalArgumentException if {@code streamSize} is less than zero, 239 * or {@code randomNumberOrigin} is not finite, 240 * or {@code randomNumberBound} is not finite, or {@code randomNumberOrigin} 241 * is greater than or equal to {@code randomNumberBound} 242 * 243 * @implSpec The default implementation produces a sequential stream that repeatedly 244 * calls {@link RandomGenerator#nextDouble(double, double) nextDouble}(randomNumberOrigin, randomNumberBound). 245 */ doubles(long streamSize, double randomNumberOrigin, double randomNumberBound)246 default DoubleStream doubles(long streamSize, double randomNumberOrigin, 247 double randomNumberBound) { 248 RandomSupport.checkStreamSize(streamSize); 249 RandomSupport.checkRange(randomNumberOrigin, randomNumberBound); 250 251 return doubles(randomNumberOrigin, randomNumberBound).limit(streamSize); 252 } 253 254 /** 255 * Returns an effectively unlimited stream of pseudorandomly chosen 256 * {@code int} values. 257 * 258 * @return a stream of pseudorandomly chosen {@code int} values 259 * 260 * @implNote It is permitted to implement this method in a manner 261 * equivalent to {@link RandomGenerator#ints(long) ints} 262 * ({@link Long#MAX_VALUE Long.MAX_VALUE}). 263 * 264 * @implSpec The default implementation produces a sequential stream 265 * that repeatedly calls {@link RandomGenerator#nextInt() nextInt}(). 266 */ ints()267 default IntStream ints() { 268 return IntStream.generate(this::nextInt).sequential(); 269 } 270 271 /** 272 * Returns an effectively unlimited stream of pseudorandomly chosen 273 * {@code int} values, where each value is between the specified origin 274 * (inclusive) and the specified bound (exclusive). 275 * 276 * @param randomNumberOrigin the least value that can be produced 277 * @param randomNumberBound the upper bound (exclusive) for each value produced 278 * 279 * @return a stream of pseudorandomly chosen {@code int} values, each between 280 * the specified origin (inclusive) and the specified bound (exclusive) 281 * 282 * @throws IllegalArgumentException if {@code randomNumberOrigin} 283 * is greater than or equal to {@code randomNumberBound} 284 * 285 * @implNote It is permitted to implement this method in a manner equivalent to 286 * {@link RandomGenerator#ints(long, int, int) ints} 287 * ({@link Long#MAX_VALUE Long.MAX_VALUE}, randomNumberOrigin, randomNumberBound). 288 * 289 * @implSpec The default implementation produces a sequential stream that repeatedly 290 * calls {@link RandomGenerator#nextInt(int, int) nextInt}(randomNumberOrigin, randomNumberBound). 291 */ ints(int randomNumberOrigin, int randomNumberBound)292 default IntStream ints(int randomNumberOrigin, int randomNumberBound) { 293 RandomSupport.checkRange(randomNumberOrigin, randomNumberBound); 294 295 return IntStream.generate(() -> nextInt(randomNumberOrigin, randomNumberBound)).sequential(); 296 } 297 298 /** 299 * Returns a stream producing the given {@code streamSize} number of 300 * pseudorandomly chosen {@code int} values. 301 * 302 * @param streamSize the number of values to generate 303 * 304 * @return a stream of pseudorandomly chosen {@code int} values 305 * 306 * @throws IllegalArgumentException if {@code streamSize} is 307 * less than zero 308 * 309 * @implSpec The default implementation produces a sequential stream 310 * that repeatedly calls {@link RandomGenerator#nextInt() nextInt}(). 311 */ ints(long streamSize)312 default IntStream ints(long streamSize) { 313 RandomSupport.checkStreamSize(streamSize); 314 315 return ints().limit(streamSize); 316 } 317 318 /** 319 * Returns a stream producing the given {@code streamSize} number of 320 * pseudorandomly chosen {@code int} values, where each value is between 321 * the specified origin (inclusive) and the specified bound (exclusive). 322 * 323 * @param streamSize the number of values to generate 324 * @param randomNumberOrigin the least value that can be produced 325 * @param randomNumberBound the upper bound (exclusive) for each value produced 326 * 327 * @return a stream of pseudorandomly chosen {@code int} values, each between 328 * the specified origin (inclusive) and the specified bound (exclusive) 329 * 330 * @throws IllegalArgumentException if {@code streamSize} is 331 * less than zero, or {@code randomNumberOrigin} 332 * is greater than or equal to {@code randomNumberBound} 333 * 334 * @implSpec The default implementation produces a sequential stream that repeatedly 335 * calls {@link RandomGenerator#nextInt(int, int) nextInt}(randomNumberOrigin, randomNumberBound). 336 */ ints(long streamSize, int randomNumberOrigin, int randomNumberBound)337 default IntStream ints(long streamSize, int randomNumberOrigin, 338 int randomNumberBound) { 339 RandomSupport.checkStreamSize(streamSize); 340 RandomSupport.checkRange(randomNumberOrigin, randomNumberBound); 341 342 return ints(randomNumberOrigin, randomNumberBound).limit(streamSize); 343 } 344 345 /** 346 * Returns an effectively unlimited stream of pseudorandomly chosen 347 * {@code long} values. 348 * 349 * @return a stream of pseudorandomly chosen {@code long} values 350 * 351 * @implNote It is permitted to implement this method in a manner 352 * equivalent to {@link RandomGenerator#longs(long) longs} 353 * ({@link Long#MAX_VALUE Long.MAX_VALUE}). 354 * 355 * @implSpec The default implementation produces a sequential stream 356 * that repeatedly calls {@link RandomGenerator#nextLong() nextLong}(). 357 */ longs()358 default LongStream longs() { 359 return LongStream.generate(this::nextLong).sequential(); 360 } 361 362 /** 363 * Returns an effectively unlimited stream of pseudorandomly chosen 364 * {@code long} values, where each value is between the specified origin 365 * (inclusive) and the specified bound (exclusive). 366 * 367 * @param randomNumberOrigin the least value that can be produced 368 * @param randomNumberBound the upper bound (exclusive) for each value produced 369 * 370 * @return a stream of pseudorandomly chosen {@code long} values, each between 371 * the specified origin (inclusive) and the specified bound (exclusive) 372 * 373 * @throws IllegalArgumentException if {@code randomNumberOrigin} 374 * is greater than or equal to {@code randomNumberBound} 375 * 376 * @implNote It is permitted to implement this method in a manner equivalent to 377 * {@link RandomGenerator#longs(long, long, long) longs} 378 * ({@link Long#MAX_VALUE Long.MAX_VALUE}, randomNumberOrigin, randomNumberBound). 379 * 380 * @implSpec The default implementation produces a sequential stream that repeatedly 381 * calls {@link RandomGenerator#nextLong(long, long) nextLong}(randomNumberOrigin, randomNumberBound). 382 */ longs(long randomNumberOrigin, long randomNumberBound)383 default LongStream longs(long randomNumberOrigin, long randomNumberBound) { 384 RandomSupport.checkRange(randomNumberOrigin, randomNumberBound); 385 386 return LongStream.generate(() -> nextLong(randomNumberOrigin, randomNumberBound)).sequential(); 387 } 388 389 /** 390 * Returns a stream producing the given {@code streamSize} number of 391 * pseudorandomly chosen {@code long} values. 392 * 393 * @param streamSize the number of values to generate 394 * 395 * @return a stream of pseudorandomly chosen {@code long} values 396 * 397 * @throws IllegalArgumentException if {@code streamSize} is 398 * less than zero 399 * 400 * @implSpec The default implementation produces a sequential stream 401 * that repeatedly calls {@link RandomGenerator#nextLong() nextLong}(). 402 */ longs(long streamSize)403 default LongStream longs(long streamSize) { 404 RandomSupport.checkStreamSize(streamSize); 405 406 return longs().limit(streamSize); 407 } 408 409 /** 410 * Returns a stream producing the given {@code streamSize} number of 411 * pseudorandomly chosen {@code long} values, where each value is between 412 * the specified origin (inclusive) and the specified bound (exclusive). 413 * 414 * @param streamSize the number of values to generate 415 * @param randomNumberOrigin the least value that can be produced 416 * @param randomNumberBound the upper bound (exclusive) for each value produced 417 * 418 * @return a stream of pseudorandomly chosen {@code long} values, each between 419 * the specified origin (inclusive) and the specified bound (exclusive) 420 * 421 * @throws IllegalArgumentException if {@code streamSize} is 422 * less than zero, or {@code randomNumberOrigin} 423 * is greater than or equal to {@code randomNumberBound} 424 * 425 * @implSpec The default implementation produces a sequential stream that repeatedly 426 * calls {@link RandomGenerator#nextLong(long, long) nextLong}(randomNumberOrigin, randomNumberBound). 427 */ longs(long streamSize, long randomNumberOrigin, long randomNumberBound)428 default LongStream longs(long streamSize, long randomNumberOrigin, 429 long randomNumberBound) { 430 RandomSupport.checkStreamSize(streamSize); 431 RandomSupport.checkRange(randomNumberOrigin, randomNumberBound); 432 433 return longs(randomNumberOrigin, randomNumberBound).limit(streamSize); 434 } 435 436 /** 437 * Returns a pseudorandomly chosen {@code boolean} value. 438 * 439 * <p> The default implementation tests the high-order bit (sign bit) of a 440 * value produced by {@link RandomGenerator#nextInt() nextInt}(), on the 441 * grounds that some algorithms for pseudorandom number generation produce 442 * values whose high-order bits have better statistical quality than the 443 * low-order bits. 444 * 445 * @return a pseudorandomly chosen {@code boolean} value 446 * 447 * @implSpec The default implementation produces a result based on the 448 * sign bit of a number generated by {@link #nextInt()}. 449 */ nextBoolean()450 default boolean nextBoolean() { 451 return nextInt() < 0; 452 } 453 454 /** 455 * Fills a user-supplied byte array with generated byte values 456 * pseudorandomly chosen uniformly from the range of values between -128 457 * (inclusive) and 127 (inclusive). 458 * 459 * @implNote Algorithm used to fill the byte array; 460 * <pre>{@code 461 * void nextBytes(byte[] bytes) { 462 * int i = 0; 463 * int len = bytes.length; 464 * for (int words = len >> 3; words--> 0; ) { 465 * long rnd = nextLong(); 466 * for (int n = 8; n--> 0; rnd >>>= Byte.SIZE) 467 * bytes[i++] = (byte)rnd; 468 * } 469 * if (i < len) 470 * for (long rnd = nextLong(); i < len; rnd >>>= Byte.SIZE) 471 * bytes[i++] = (byte)rnd; 472 * }}</pre> 473 * 474 * @param bytes the byte array to fill with pseudorandom bytes 475 * @throws NullPointerException if bytes is null 476 * 477 * @implSpec The default implementation produces results from repeated calls 478 * to {@link #nextLong()}. 479 */ nextBytes(byte[] bytes)480 default void nextBytes(byte[] bytes) { 481 int i = 0; 482 int len = bytes.length; 483 for (int words = len >> 3; words--> 0; ) { 484 long rnd = nextLong(); 485 for (int n = 8; n--> 0; rnd >>>= Byte.SIZE) 486 bytes[i++] = (byte)rnd; 487 } 488 if (i < len) 489 for (long rnd = nextLong(); i < len; rnd >>>= Byte.SIZE) 490 bytes[i++] = (byte)rnd; 491 } 492 493 /** 494 * Returns a pseudorandom {@code float} value between zero (inclusive) and 495 * one (exclusive). 496 * 497 * @return a pseudorandom {@code float} value between zero (inclusive) and one (exclusive) 498 * 499 * @implSpec The default implementation uses the 24 high-order bits from a call to 500 * {@link RandomGenerator#nextInt() nextInt}(). 501 */ nextFloat()502 default float nextFloat() { 503 return (nextInt() >>> 8) * 0x1.0p-24f; 504 } 505 506 /** 507 * Returns a pseudorandomly chosen {@code float} value between zero 508 * (inclusive) and the specified bound (exclusive). 509 * 510 * @param bound the upper bound (exclusive) for the returned value. 511 * Must be positive and finite 512 * 513 * @return a pseudorandomly chosen {@code float} value between 514 * zero (inclusive) and the bound (exclusive) 515 * 516 * @throws IllegalArgumentException if {@code bound} is not 517 * both positive and finite 518 * 519 * @implSpec The default implementation checks that {@code bound} is a 520 * positive finite float. Then invokes {@code nextFloat()}, scaling 521 * the result so that the final result lies between {@code 0.0f} (inclusive) 522 * and {@code bound} (exclusive). 523 */ nextFloat(float bound)524 default float nextFloat(float bound) { 525 RandomSupport.checkBound(bound); 526 527 return RandomSupport.boundedNextFloat(this, bound); 528 } 529 530 /** 531 * Returns a pseudorandomly chosen {@code float} value between the 532 * specified origin (inclusive) and the specified bound (exclusive). 533 * 534 * @param origin the least value that can be returned 535 * @param bound the upper bound (exclusive) 536 * 537 * @return a pseudorandomly chosen {@code float} value between the 538 * origin (inclusive) and the bound (exclusive) 539 * 540 * @throws IllegalArgumentException if {@code origin} is not finite, 541 * or {@code bound} is not finite, or {@code origin} 542 * is greater than or equal to {@code bound} 543 * 544 * @implSpec The default implementation checks that {@code origin} and 545 * {@code bound} are positive finite floats. Then invokes 546 * {@code nextFloat()}, scaling and translating the result so that the final 547 * result lies between {@code origin} (inclusive) and {@code bound} 548 * (exclusive). 549 */ nextFloat(float origin, float bound)550 default float nextFloat(float origin, float bound) { 551 RandomSupport.checkRange(origin, bound); 552 553 return RandomSupport.boundedNextFloat(this, origin, bound); 554 } 555 556 /** 557 * Returns a pseudorandom {@code double} value between zero (inclusive) and 558 * one (exclusive). 559 * 560 * @return a pseudorandom {@code double} value between zero (inclusive) 561 * and one (exclusive) 562 * 563 * @implSpec The default implementation uses the 53 high-order bits from a call to 564 * {@link RandomGenerator#nextLong nextLong}(). 565 */ nextDouble()566 default double nextDouble() { 567 return (nextLong() >>> 11) * 0x1.0p-53; 568 } 569 570 /** 571 * Returns a pseudorandomly chosen {@code double} value between zero 572 * (inclusive) and the specified bound (exclusive). 573 * 574 * @param bound the upper bound (exclusive) for the returned value. 575 * Must be positive and finite 576 * 577 * @return a pseudorandomly chosen {@code double} value between 578 * zero (inclusive) and the bound (exclusive) 579 * 580 * @throws IllegalArgumentException if {@code bound} is not 581 * both positive and finite 582 * 583 * @implSpec The default implementation checks that {@code bound} is a 584 * positive finite double. Then invokes {@code nextDouble()}, scaling 585 * the result so that the final result lies between {@code 0.0} (inclusive) 586 * and {@code bound} (exclusive). 587 */ nextDouble(double bound)588 default double nextDouble(double bound) { 589 RandomSupport.checkBound(bound); 590 591 return RandomSupport.boundedNextDouble(this, bound); 592 } 593 594 /** 595 * Returns a pseudorandomly chosen {@code double} value between the 596 * specified origin (inclusive) and the specified bound (exclusive). 597 * 598 * @param origin the least value that can be returned 599 * @param bound the upper bound (exclusive) for the returned value 600 * 601 * @return a pseudorandomly chosen {@code double} value between the 602 * origin (inclusive) and the bound (exclusive) 603 * 604 * @throws IllegalArgumentException if {@code origin} is not finite, 605 * or {@code bound} is not finite, or {@code origin} 606 * is greater than or equal to {@code bound} 607 * 608 * @implSpec The default implementation checks that {@code origin} and 609 * {@code bound} are positive finite doubles. Then calls 610 * {@code nextDouble()}, scaling and translating the result so that the final 611 * result lies between {@code origin} (inclusive) and {@code bound} 612 * (exclusive). 613 */ nextDouble(double origin, double bound)614 default double nextDouble(double origin, double bound) { 615 RandomSupport.checkRange(origin, bound); 616 617 return RandomSupport.boundedNextDouble(this, origin, bound); 618 } 619 620 /** 621 * Returns a pseudorandomly chosen {@code int} value. 622 * 623 * @return a pseudorandomly chosen {@code int} value 624 * 625 * @implSpec The default implementation uses the 32 high-order bits from a call to 626 * {@link RandomGenerator#nextLong nextLong}(). 627 */ nextInt()628 default int nextInt() { 629 return (int)(nextLong() >>> 32); 630 } 631 632 /** 633 * Returns a pseudorandomly chosen {@code int} value between zero 634 * (inclusive) and the specified bound (exclusive). 635 * 636 * @param bound the upper bound (exclusive) for the returned value. 637 * Must be positive. 638 * 639 * @return a pseudorandomly chosen {@code int} value between 640 * zero (inclusive) and the bound (exclusive) 641 * 642 * @throws IllegalArgumentException if {@code bound} is not positive 643 * 644 * @implSpec The default implementation checks that {@code bound} is a 645 * positive {@code int}. Then invokes {@code nextInt()}, limiting the result 646 * to be greater than or equal zero and less than {@code bound}. If {@code bound} 647 * is a power of two then limiting is a simple masking operation. Otherwise, 648 * the result is re-calculated by invoking {@code nextInt()} until the 649 * result is greater than or equal zero and less than {@code bound}. 650 */ nextInt(int bound)651 default int nextInt(int bound) { 652 RandomSupport.checkBound(bound); 653 654 return RandomSupport.boundedNextInt(this, bound); 655 } 656 657 /** 658 * Returns a pseudorandomly chosen {@code int} value between the specified 659 * origin (inclusive) and the specified bound (exclusive). 660 * 661 * @param origin the least value that can be returned 662 * @param bound the upper bound (exclusive) for the returned value 663 * 664 * @return a pseudorandomly chosen {@code int} value between the 665 * origin (inclusive) and the bound (exclusive) 666 * 667 * @throws IllegalArgumentException if {@code origin} is greater than 668 * or equal to {@code bound} 669 * 670 * @implSpec The default implementation checks that {@code origin} and 671 * {@code bound} are positive {@code ints}. Then invokes {@code nextInt()}, 672 * limiting the result to be greater that or equal {@code origin} and less 673 * than {@code bound}. If {@code bound} is a power of two then limiting is a 674 * simple masking operation. Otherwise, the result is re-calculated by 675 * invoking {@code nextInt()} until the result is greater than or equal 676 * {@code origin} and less than {@code bound}. 677 */ nextInt(int origin, int bound)678 default int nextInt(int origin, int bound) { 679 RandomSupport.checkRange(origin, bound); 680 681 return RandomSupport.boundedNextInt(this, origin, bound); 682 } 683 684 /** 685 * Returns a pseudorandomly chosen {@code long} value. 686 * 687 * @return a pseudorandomly chosen {@code long} value 688 */ nextLong()689 long nextLong(); 690 691 /** 692 * Returns a pseudorandomly chosen {@code long} value between zero 693 * (inclusive) and the specified bound (exclusive). 694 * 695 * @param bound the upper bound (exclusive) for the returned value. 696 * Must be positive. 697 * 698 * @return a pseudorandomly chosen {@code long} value between 699 * zero (inclusive) and the bound (exclusive) 700 * 701 * @throws IllegalArgumentException if {@code bound} is not positive 702 * 703 * @implSpec The default implementation checks that {@code bound} is a 704 * positive {@code long}. Then invokes {@code nextLong()}, limiting the 705 * result to be greater than or equal zero and less than {@code bound}. If 706 * {@code bound} is a power of two then limiting is a simple masking 707 * operation. Otherwise, the result is re-calculated by invoking 708 * {@code nextLong()} until the result is greater than or equal zero and 709 * less than {@code bound}. 710 */ nextLong(long bound)711 default long nextLong(long bound) { 712 RandomSupport.checkBound(bound); 713 714 return RandomSupport.boundedNextLong(this, bound); 715 } 716 717 /** 718 * Returns a pseudorandomly chosen {@code long} value between the 719 * specified origin (inclusive) and the specified bound (exclusive). 720 * 721 * @param origin the least value that can be returned 722 * @param bound the upper bound (exclusive) for the returned value 723 * 724 * @return a pseudorandomly chosen {@code long} value between the 725 * origin (inclusive) and the bound (exclusive) 726 * 727 * @throws IllegalArgumentException if {@code origin} is greater than 728 * or equal to {@code bound} 729 * 730 * @implSpec The default implementation checks that {@code origin} and 731 * {@code bound} are positive {@code longs}. Then invokes {@code nextLong()}, 732 * limiting the result to be greater than or equal {@code origin} and less 733 * than {@code bound}. If {@code bound} is a power of two then limiting is a 734 * simple masking operation. Otherwise, the result is re-calculated by 735 * invoking {@code nextLong()} until the result is greater than or equal 736 * {@code origin} and less than {@code bound}. 737 */ nextLong(long origin, long bound)738 default long nextLong(long origin, long bound) { 739 RandomSupport.checkRange(origin, bound); 740 741 return RandomSupport.boundedNextLong(this, origin, bound); 742 } 743 744 /** 745 * Returns a {@code double} value pseudorandomly chosen from a Gaussian 746 * (normal) distribution whose mean is 0 and whose standard deviation is 1. 747 * 748 * @return a {@code double} value pseudorandomly chosen from a 749 * Gaussian distribution 750 * 751 * @implSpec The default implementation uses McFarland's fast modified 752 * ziggurat algorithm (largely table-driven, with rare cases handled by 753 * computation and rejection sampling). Walker's alias method for sampling 754 * a discrete distribution also plays a role. 755 */ nextGaussian()756 default double nextGaussian() { 757 // See Knuth, TAOCP, Vol. 2, 3rd edition, Section 3.4.1 Algorithm C. 758 return RandomSupport.computeNextGaussian(this); 759 } 760 761 /** 762 * Returns a {@code double} value pseudorandomly chosen from a Gaussian 763 * (normal) distribution with a mean and standard deviation specified by the 764 * arguments. 765 * 766 * @param mean the mean of the Gaussian distribution to be drawn from 767 * @param stddev the standard deviation (square root of the variance) 768 * of the Gaussian distribution to be drawn from 769 * 770 * @return a {@code double} value pseudorandomly chosen from the 771 * specified Gaussian distribution 772 * 773 * @throws IllegalArgumentException if {@code stddev} is negative 774 * 775 * @implSpec The default implementation uses McFarland's fast modified 776 * ziggurat algorithm (largely table-driven, with rare cases handled by 777 * computation and rejection sampling). Walker's alias method for sampling 778 * a discrete distribution also plays a role. 779 */ nextGaussian(double mean, double stddev)780 default double nextGaussian(double mean, double stddev) { 781 if (stddev < 0.0) throw new IllegalArgumentException("standard deviation must be non-negative"); 782 783 return mean + stddev * RandomSupport.computeNextGaussian(this); 784 } 785 786 /** 787 * Returns a nonnegative {@code double} value pseudorandomly chosen from 788 * an exponential distribution whose mean is 1. 789 * 790 * @return a nonnegative {@code double} value pseudorandomly chosen from an 791 * exponential distribution 792 * 793 * @implSpec The default implementation uses McFarland's fast modified 794 * ziggurat algorithm (largely table-driven, with rare cases handled by 795 * computation and rejection sampling). Walker's alias method for sampling 796 * a discrete distribution also plays a role. 797 */ nextExponential()798 default double nextExponential() { 799 return RandomSupport.computeNextExponential(this); 800 } 801 802 /** 803 * The {@link StreamableGenerator} interface augments the 804 * {@link RandomGenerator} interface to provide methods that return streams 805 * of {@link RandomGenerator} objects. Ideally, such a stream of objects 806 * would have the property that the behavior of each object is statistically 807 * independent of all the others. In practice, one may have to settle for 808 * some approximation to this property. 809 * 810 * <p> A generator that implements interface {@link SplittableGenerator} may 811 * choose to use its {@link SplittableGenerator#splits splits}() method to 812 * implement the {@link StreamableGenerator#rngs rngs}() method required by this 813 * interface. 814 * 815 * <p> A generator that implements interface {@link JumpableGenerator} may 816 * choose to use its {@link JumpableGenerator#jumps() jumps}() method to implement the 817 * {@link StreamableGenerator#rngs() rngs}() method required by this interface. 818 * 819 * <p> A generator that implements interface {@link LeapableGenerator} may 820 * choose to use its {@link LeapableGenerator#leaps() leaps}() method to 821 * implement the {@link StreamableGenerator#rngs() rngs}() method required by this 822 * interface. 823 * 824 * <p> Objects that implement {@link StreamableGenerator} are typically not 825 * cryptographically secure. Consider instead using {@link SecureRandom} to 826 * get a cryptographically secure pseudo-random number generator for use by 827 * security-sensitive applications. 828 */ 829 interface StreamableGenerator extends RandomGenerator { 830 831 /** 832 * Returns an instance of {@link StreamableGenerator} that utilizes the 833 * {@code name} <a href="package-summary.html#algorithms">algorithm</a>. 834 * 835 * @param name Name of random number generator 836 * <a href="package-summary.html#algorithms">algorithm</a> 837 * 838 * @return An instance of {@link StreamableGenerator} 839 * 840 * @throws NullPointerException if name is null 841 * @throws IllegalArgumentException if the named algorithm is not found 842 */ of(String name)843 static StreamableGenerator of(String name) { 844 Objects.requireNonNull(name); 845 846 return RandomGeneratorFactory.of(name, StreamableGenerator.class); 847 } 848 849 /** 850 * Returns an effectively unlimited stream of objects, each of which 851 * implements the {@link RandomGenerator} interface. Ideally the 852 * generators in the stream will appear to be statistically independent. 853 * The new generators are of the same 854 * <a href="package-summary.html#algorithms">algorithm</a> as this generator. 855 * 856 * @return a stream of objects that implement the {@link RandomGenerator} interface 857 * 858 * @implNote It is permitted to implement this method in a manner 859 * equivalent to {@link StreamableGenerator#rngs(long) rngs} 860 * ({@link Long#MAX_VALUE Long.MAX_VALUE}). 861 */ rngs()862 Stream<RandomGenerator> rngs(); 863 864 /** 865 * Returns an effectively unlimited stream of objects, each of which 866 * implements the {@link RandomGenerator} interface. Ideally the 867 * generators in the stream will appear to be statistically independent. 868 * The new generators are of the same 869 * <a href="package-summary.html#algorithms">algorithm</a> as this generator. 870 * 871 * @param streamSize the number of generators to generate 872 * 873 * @return a stream of objects that implement the {@link RandomGenerator} interface 874 * 875 * @throws IllegalArgumentException if {@code streamSize} is 876 * less than zero 877 * 878 * @implSpec The default implementation calls {@link StreamableGenerator#rngs() rngs}() and 879 * then limits its length to {@code streamSize}. 880 */ rngs(long streamSize)881 default Stream<RandomGenerator> rngs(long streamSize) { 882 RandomSupport.checkStreamSize(streamSize); 883 884 return rngs().limit(streamSize); 885 } 886 } 887 888 /** 889 * This interface is designed to provide a common protocol for objects that 890 * generate sequences of pseudorandom values and can be <i>split</i> into 891 * two objects (the original one and a new one) each of which obey that same 892 * protocol (and therefore can be recursively split indefinitely). 893 * 894 * <p> Ideally, all {@link SplittableGenerator} objects produced by 895 * recursive splitting from a single original {@link SplittableGenerator} 896 * object are statistically independent of one another and individually 897 * uniform. Therefore we would expect the set of values collectively 898 * generated by a set of such objects to have the same statistical 899 * properties as if the same quantity of values were generated by a single 900 * thread using a single {@link SplittableGenerator} object. In practice, 901 * one must settle for some approximation to independence and uniformity. 902 * 903 * <p> Methods are provided to perform a single splitting operation and also 904 * to produce a stream of generators split off from the original (by either 905 * iterative or recursive splitting, or a combination). 906 * 907 * <p> Objects that implement {@link SplittableGenerator} are typically not 908 * cryptographically secure. Consider instead using {@link SecureRandom} to 909 * get a cryptographically secure pseudo-random number generator for use by 910 * security-sensitive applications. 911 */ 912 interface SplittableGenerator extends StreamableGenerator { 913 914 /** 915 * Returns an instance of {@link SplittableGenerator} that utilizes the 916 * {@code name} <a href="package-summary.html#algorithms">algorithm</a>. 917 * 918 * @param name Name of random number generator 919 * <a href="package-summary.html#algorithms">algorithm</a> 920 * 921 * @return An instance of {@link SplittableGenerator} 922 * 923 * @throws NullPointerException if name is null 924 * @throws IllegalArgumentException if the named algorithm is not found 925 */ of(String name)926 static SplittableGenerator of(String name) { 927 Objects.requireNonNull(name); 928 929 return RandomGeneratorFactory.of(name, SplittableGenerator.class); 930 } 931 932 /** 933 * Returns a new pseudorandom number generator, split off from this one, 934 * that implements the {@link RandomGenerator} and 935 * {@link SplittableGenerator} interfaces. 936 * 937 * <p> This pseudorandom number generator may be used as a source of 938 * pseudorandom bits used to initialize the state of the new one. 939 * 940 * @return a new object that implements the {@link RandomGenerator} and 941 * {@link SplittableGenerator} interfaces 942 */ split()943 SplittableGenerator split(); 944 945 /** 946 * Returns a new pseudorandom number generator, split off from this one, 947 * that implements the {@link RandomGenerator} and 948 * {@link SplittableGenerator} interfaces. 949 * 950 * @param source a {@link SplittableGenerator} instance to be used instead 951 * of this one as a source of pseudorandom bits used to 952 * initialize the state of the new ones. 953 * 954 * @return an object that implements the {@link RandomGenerator} and 955 * {@link SplittableGenerator} interfaces 956 * 957 * @throws NullPointerException if source is null 958 */ split(SplittableGenerator source)959 SplittableGenerator split(SplittableGenerator source); 960 961 /** 962 * Returns an effectively unlimited stream of new pseudorandom number 963 * generators, each of which implements the {@link SplittableGenerator} 964 * interface. 965 * 966 * <p> This pseudorandom number generator may be used as a source of 967 * pseudorandom bits used to initialize the state the new ones. 968 * 969 * @implNote It is permitted to implement this method in a manner 970 * equivalent to {@link SplittableGenerator#splits(long) splits} 971 * ({@link Long#MAX_VALUE Long.MAX_VALUE}). 972 * 973 * @return a stream of {@link SplittableGenerator} objects 974 * 975 * @implSpec The default implementation invokes 976 * {@link SplittableGenerator#splits(SplittableGenerator) splits(this)}. 977 */ splits()978 default Stream<SplittableGenerator> splits() { 979 return this.splits(this); 980 } 981 982 /** 983 * Returns a stream producing the given {@code streamSize} number of new 984 * pseudorandom number generators, each of which implements the 985 * {@link SplittableGenerator} interface. 986 * 987 * <p> This pseudorandom number generator may be used as a source of 988 * pseudorandom bits used to initialize the state the new ones. 989 * 990 * @param streamSize the number of values to generate 991 * 992 * @return a stream of {@link SplittableGenerator} objects 993 * 994 * @throws IllegalArgumentException if {@code streamSize} is 995 * less than zero 996 */ splits(long streamSize)997 Stream<SplittableGenerator> splits(long streamSize); 998 999 /** 1000 * Returns an effectively unlimited stream of new pseudorandom number 1001 * generators, each of which implements the {@link SplittableGenerator} 1002 * interface. 1003 * 1004 * @param source a {@link SplittableGenerator} instance to be used instead 1005 * of this one as a source of pseudorandom bits used to 1006 * initialize the state of the new ones. 1007 * 1008 * @return a stream of {@link SplittableGenerator} objects 1009 * 1010 * @implNote It is permitted to implement this method in a manner 1011 * equivalent to {@link SplittableGenerator#splits(long, SplittableGenerator) splits} 1012 * ({@link Long#MAX_VALUE Long.MAX_VALUE}, source). 1013 * 1014 * @throws NullPointerException if source is null 1015 */ splits(SplittableGenerator source)1016 Stream<SplittableGenerator> splits(SplittableGenerator source); 1017 1018 /** 1019 * Returns a stream producing the given {@code streamSize} number of new 1020 * pseudorandom number generators, each of which implements the 1021 * {@link SplittableGenerator} interface. 1022 * 1023 * @param streamSize the number of values to generate 1024 * @param source a {@link SplittableGenerator} instance to be used instead 1025 * of this one as a source of pseudorandom bits used to 1026 * initialize the state of the new ones. 1027 * 1028 * @return a stream of {@link SplittableGenerator} objects 1029 * 1030 * @throws IllegalArgumentException if {@code streamSize} is 1031 * less than zero 1032 * @throws NullPointerException if source is null 1033 */ splits(long streamSize, SplittableGenerator source)1034 Stream<SplittableGenerator> splits(long streamSize, SplittableGenerator source); 1035 1036 /** 1037 * Returns an effectively unlimited stream of new pseudorandom number 1038 * generators, each of which implements the {@link RandomGenerator} 1039 * interface. Ideally the generators in the stream will appear to be 1040 * statistically independent. 1041 * 1042 * @return a stream of objects that implement the {@link RandomGenerator} interface 1043 * 1044 * @implSpec The default implementation calls {@link SplittableGenerator#splits() splits}(). 1045 */ rngs()1046 default Stream<RandomGenerator> rngs() { 1047 return this.splits().map(x -> x); 1048 } 1049 1050 /** 1051 * Returns a stream producing the given {@code streamSize} number of new 1052 * pseudorandom number generators, each of which implements the 1053 * {@link RandomGenerator} interface. Ideally the generators in the 1054 * stream will appear to be statistically independent. 1055 * 1056 * @param streamSize the number of generators to generate 1057 * 1058 * @return a stream of objects that implement the {@link RandomGenerator} interface 1059 * 1060 * @throws IllegalArgumentException if {@code streamSize} is 1061 * less than zero 1062 * 1063 * @implSpec The default implementation calls {@link SplittableGenerator#splits(long) splits}(streamSize). 1064 */ rngs(long streamSize)1065 default Stream<RandomGenerator> rngs(long streamSize) { 1066 return this.splits(streamSize).map(x -> x); 1067 } 1068 } 1069 1070 /** 1071 * This interface is designed to provide a common protocol for objects that 1072 * generate pseudorandom values and can easily <i>jump</i> forward, by a 1073 * moderate amount (ex. 2<sup>64</sup>) to a distant point in the state cycle. 1074 * 1075 * <p> Ideally, all {@link JumpableGenerator} objects produced by iterative 1076 * jumping from a single original {@link JumpableGenerator} object are 1077 * statistically independent of one another and individually uniform. In 1078 * practice, one must settle for some approximation to independence and 1079 * uniformity. In particular, a specific implementation may assume that each 1080 * generator in a stream produced by the 1081 * {@link JumpableGenerator#jump jump()} method is used to produce a number 1082 * of values no larger than either 2<sup>64</sup> or the square root of its 1083 * period. Implementors are advised to use algorithms whose period is at 1084 * least 2<sup>127</sup>. 1085 * 1086 * <p> Methods are provided to perform a single jump operation and also to 1087 * produce a stream of generators produced from the original by iterative 1088 * copying and jumping of internal state. A typical strategy for a 1089 * multithreaded application is to create a single {@link JumpableGenerator} 1090 * object, calls its {@link JumpableGenerator#jump jump}() method exactly 1091 * once, and then parcel out generators from the resulting stream, one to 1092 * each thread. It is generally not a good idea to call 1093 * {@link JumpableGenerator#jump jump}() on a generator that was itself 1094 * produced by the {@link JumpableGenerator#jump jump}() method, because the 1095 * result may be a generator identical to another generator already produce 1096 * by that call to the {@link JumpableGenerator#jump jump}() method. For 1097 * this reason, the return type of the {@link JumpableGenerator#jumps jumps}() 1098 * method is {@code Stream<RandomGenerator>} rather than 1099 * {@code Stream<JumpableGenerator>}, even though the actual generator 1100 * objects in that stream likely do also implement the 1101 * {@link JumpableGenerator} interface. 1102 * 1103 * <p> Objects that implement {@link JumpableGenerator} are typically not 1104 * cryptographically secure. Consider instead using {@link SecureRandom} to 1105 * get a cryptographically secure pseudo-random number generator for use by 1106 * security-sensitive applications. 1107 */ 1108 interface JumpableGenerator extends StreamableGenerator { 1109 1110 /** 1111 * Returns an instance of {@link JumpableGenerator} that utilizes the 1112 * {@code name} <a href="package-summary.html#algorithms">algorithm</a>. 1113 * 1114 * @param name Name of random number generator 1115 * <a href="package-summary.html#algorithms">algorithm</a> 1116 * 1117 * @return An instance of {@link JumpableGenerator} 1118 * 1119 * @throws NullPointerException if name is null 1120 * @throws IllegalArgumentException if the named algorithm is not found 1121 */ of(String name)1122 static JumpableGenerator of(String name) { 1123 Objects.requireNonNull(name); 1124 1125 return RandomGeneratorFactory.of(name, JumpableGenerator.class); 1126 } 1127 1128 /** 1129 * Returns a new generator whose internal state is an exact copy of this 1130 * generator (therefore their future behavior should be identical if 1131 * subjected to the same series of operations). 1132 * 1133 * @return a new object that is a copy of this generator 1134 */ copy()1135 JumpableGenerator copy(); 1136 1137 /** 1138 * Alter the state of this pseudorandom number generator so as to jump 1139 * forward a large, fixed distance (typically 2<sup>64</sup> or more) 1140 * within its state cycle. 1141 */ jump()1142 void jump(); 1143 1144 /** 1145 * Returns the distance by which the 1146 * {@link JumpableGenerator#jump jump}() method will jump forward within 1147 * the state cycle of this generator object. 1148 * 1149 * @return the default jump distance (as a {@code double} value) 1150 */ jumpDistance()1151 double jumpDistance(); 1152 1153 /** 1154 * Returns an effectively unlimited stream of new pseudorandom number 1155 * generators, each of which implements the {@link RandomGenerator} 1156 * interface. 1157 * 1158 * @return a stream of objects that implement the {@link RandomGenerator} interface 1159 * 1160 * @implNote It is permitted to implement this method in a manner equivalent to 1161 * {@link JumpableGenerator#jumps(long) jumps} 1162 * ({@link Long#MAX_VALUE Long.MAX_VALUE}). 1163 * 1164 * @implSpec The default implementation produces a sequential stream that repeatedly 1165 * calls {@link JumpableGenerator#copy copy}() and {@link JumpableGenerator#jump jump}() 1166 * on this generator, and the copies become the generators produced by the stream. 1167 */ jumps()1168 default Stream<RandomGenerator> jumps() { 1169 return Stream.generate(this::copyAndJump).sequential(); 1170 } 1171 1172 /** 1173 * Returns a stream producing the given {@code streamSize} number of new 1174 * pseudorandom number generators, each of which implements the 1175 * {@link RandomGenerator} interface. 1176 * 1177 * @param streamSize the number of generators to generate 1178 * 1179 * @return a stream of objects that implement the {@link RandomGenerator} interface 1180 * 1181 * @throws IllegalArgumentException if {@code streamSize} is less than zero 1182 * 1183 * @implSpec The default implementation produces a sequential stream that repeatedly 1184 * calls {@link JumpableGenerator#copy copy}() and {@link JumpableGenerator#jump jump}() 1185 * on this generator, and the copies become the generators produced by the stream. 1186 */ jumps(long streamSize)1187 default Stream<RandomGenerator> jumps(long streamSize) { 1188 return jumps().limit(streamSize); 1189 } 1190 1191 /** 1192 * Returns an effectively unlimited stream of new pseudorandom number 1193 * generators, each of which implements the {@link RandomGenerator} 1194 * interface. Ideally the generators in the stream will appear to be 1195 * statistically independent. 1196 * 1197 * @return a stream of objects that implement the {@link RandomGenerator} interface 1198 * 1199 * @implSpec The default implementation calls {@link JumpableGenerator#jump jump}(). 1200 */ rngs()1201 default Stream<RandomGenerator> rngs() { 1202 return this.jumps(); 1203 } 1204 1205 /** 1206 * Returns a stream producing the given {@code streamSize} number of new 1207 * pseudorandom number generators, each of which implements the 1208 * {@link RandomGenerator} interface. Ideally the generators in the 1209 * stream will appear to be statistically independent. 1210 * 1211 * @param streamSize the number of generators to generate 1212 * 1213 * @return a stream of objects that implement the {@link RandomGenerator} interface 1214 * 1215 * @throws IllegalArgumentException if {@code streamSize} is less than zero 1216 * 1217 * @implSpec The default implementation calls {@link JumpableGenerator#jumps(long) jumps}(streamSize). 1218 */ rngs(long streamSize)1219 default Stream<RandomGenerator> rngs(long streamSize) { 1220 return this.jumps(streamSize); 1221 } 1222 1223 /** 1224 * Copy this generator, jump this generator forward, then return the 1225 * copy. 1226 * 1227 * @return a copy of this generator object before the jump occurred 1228 * 1229 * @implSpec The default implementation copies this, jumps and then 1230 * returns the copy. 1231 */ copyAndJump()1232 default RandomGenerator copyAndJump() { 1233 RandomGenerator result = copy(); 1234 jump(); 1235 1236 return result; 1237 } 1238 1239 } 1240 1241 /** 1242 * This interface is designed to provide a common protocol for objects that 1243 * generate sequences of pseudorandom values and can easily not only jump 1244 * but also <i>leap</i> forward, by a large amount (ex. 2<sup>128</sup>), to 1245 * a very distant point in the state cycle. 1246 * 1247 * Typically one will construct a series of {@link LeapableGenerator} 1248 * objects by iterative leaping from a single original 1249 * {@link LeapableGenerator} object, and then for each such object produce a 1250 * subseries of objects by iterative jumping. There is little conceptual 1251 * difference between leaping and jumping, but typically a leap will be a 1252 * very long jump in the state cycle (perhaps distance 2<sup>128</sup> or 1253 * so). 1254 * 1255 * <p> Ideally, all {@link LeapableGenerator} objects produced by iterative 1256 * leaping and jumping from a single original {@link LeapableGenerator} 1257 * object are statistically independent of one another and individually 1258 * uniform. In practice, one must settle for some approximation to 1259 * independence and uniformity. In particular, a specific implementation may 1260 * assume that each generator in a stream produced by the {@code leaps} 1261 * method is used to produce (by jumping) a number of objects no larger than 1262 * 2<sup>64</sup>. Implementors are advised to use algorithms whose period 1263 * is at least 2<sup>191</sup>. 1264 * 1265 * <p> Methods are provided to perform a single leap operation and also to 1266 * produce a stream of generators produced from the original by iterative 1267 * copying and leaping of internal state. The generators produced must 1268 * implement the {@link JumpableGenerator} interface but need not also 1269 * implement the {@link LeapableGenerator} interface. A typical strategy for 1270 * a multithreaded application is to create a single 1271 * {@link LeapableGenerator} object, calls its {@code leaps} method exactly 1272 * once, and then parcel out generators from the resulting stream, one to 1273 * each thread. Then the {@link JumpableGenerator#jump() jump}() method of 1274 * each such generator be called to produce a substream of generator 1275 * objects. 1276 * 1277 * <p> Objects that implement {@link LeapableGenerator} are typically not 1278 * cryptographically secure. Consider instead using {@link SecureRandom} to 1279 * get a cryptographically secure pseudo-random number generator for use by 1280 * security-sensitive applications. 1281 */ 1282 interface LeapableGenerator extends JumpableGenerator { 1283 1284 /** 1285 * Returns an instance of {@link LeapableGenerator} that utilizes the 1286 * {@code name} <a href="package-summary.html#algorithms">algorithm</a>. 1287 * 1288 * @param name Name of random number generator 1289 * <a href="package-summary.html#algorithms">algorithm</a> 1290 * 1291 * @return An instance of {@link LeapableGenerator} 1292 * 1293 * @throws NullPointerException if name is null 1294 * @throws IllegalArgumentException if the named algorithm is not found 1295 */ of(String name)1296 static LeapableGenerator of(String name) { 1297 Objects.requireNonNull(name); 1298 1299 return RandomGeneratorFactory.of(name, LeapableGenerator.class); 1300 } 1301 1302 /** 1303 * Returns a new generator whose internal state is an exact copy of this 1304 * generator (therefore their future behavior should be identical if 1305 * subjected to the same series of operations). 1306 * 1307 * @return a new object that is a copy of this generator 1308 */ copy()1309 LeapableGenerator copy(); 1310 1311 /** 1312 * Alter the state of this pseudorandom number generator so as to leap 1313 * forward a large, fixed distance (typically 2<sup>96</sup> or more) 1314 * within its state cycle. 1315 */ leap()1316 void leap(); 1317 1318 /** 1319 * Returns the distance by which the 1320 * {@link LeapableGenerator#leap() leap}() method will leap forward within 1321 * the state cycle of this generator object. 1322 * 1323 * @return the default leap distance (as a {@code double} value) 1324 */ leapDistance()1325 double leapDistance(); 1326 1327 /** 1328 * Returns an effectively unlimited stream of new pseudorandom number 1329 * generators, each of which implements the {@link JumpableGenerator} 1330 * interface. 1331 * 1332 * @return a stream of objects that implement the {@link JumpableGenerator} interface 1333 * 1334 * @implNote It is permitted to implement this method in a manner equivalent to 1335 * {@link LeapableGenerator#leaps(long) leaps} 1336 * ({@link Long#MAX_VALUE Long.MAX_VALUE}). 1337 * 1338 * @implSpec The default implementation produces a sequential stream that repeatedly 1339 * calls {@link LeapableGenerator#copy() copy}() and {@link LeapableGenerator#leap() leap}() 1340 * on this generator, and the copies become the generators produced by the stream. 1341 */ leaps()1342 default Stream<JumpableGenerator> leaps() { 1343 return Stream.generate(this::copyAndLeap).sequential(); 1344 } 1345 1346 /** 1347 * Returns a stream producing the given {@code streamSize} number of new 1348 * pseudorandom number generators, each of which implements the 1349 * {@link JumpableGenerator} interface. 1350 * 1351 * @param streamSize the number of generators to generate 1352 * 1353 * @return a stream of objects that implement the {@link JumpableGenerator} interface 1354 * 1355 * @throws IllegalArgumentException if {@code streamSize} is less than zero 1356 * 1357 * @implSpec The default implementation produces a sequential stream that repeatedly 1358 * calls {@link LeapableGenerator#copy() copy}() and {@link LeapableGenerator#leap() leap}() 1359 * on this generator, and the copies become the generators produced by the stream. 1360 */ leaps(long streamSize)1361 default Stream<JumpableGenerator> leaps(long streamSize) { 1362 return leaps().limit(streamSize); 1363 } 1364 1365 /** 1366 * Copy this generator, leap this generator forward, then return the 1367 * copy. 1368 * 1369 * @return a copy of this generator object before the leap occurred 1370 * 1371 * @implSpec The default implementation copies this, leaps and then 1372 * returns the copy. 1373 */ copyAndLeap()1374 default JumpableGenerator copyAndLeap() { 1375 JumpableGenerator result = copy(); 1376 leap(); 1377 return result; 1378 } 1379 1380 } 1381 1382 /** 1383 * This interface is designed to provide a common protocol for objects that 1384 * generate sequences of pseudorandom values and can easily <i>jump</i> 1385 * forward, by an arbitrary amount, to a distant point in the state cycle. 1386 * 1387 * <p> Ideally, all {@link ArbitrarilyJumpableGenerator} objects produced by 1388 * iterative jumping from a single original 1389 * {@link ArbitrarilyJumpableGenerator} object are statistically independent 1390 * of one another and individually uniform, provided that they do not 1391 * traverse overlapping portions of the state cycle. In practice, one must 1392 * settle for some approximation to independence and uniformity. In 1393 * particular, a specific implementation may assume that each generator in a 1394 * stream produced by the {@link JumpableGenerator#jump() jump}() method is 1395 * used to produce a number of values no larger than the jump distance 1396 * specified. Implementors are advised to use algorithms whose period is at 1397 * least 2<sup>127</sup>. 1398 * 1399 * <p> For many applications, it suffices to jump forward by a power of two 1400 * or some small multiple of a power of two, but this power of two may not 1401 * be representable as a {@code long} value. To avoid the use of 1402 * {@link BigInteger} values as jump distances, {@code double} values are 1403 * used instead. 1404 * 1405 * <p> Methods are provided to perform a single jump operation and also to 1406 * produce a stream of generators produced from the original by iterative 1407 * copying and jumping of internal state. A typical strategy for a 1408 * multithreaded application is to create a single 1409 * {@link ArbitrarilyJumpableGenerator} object, call its 1410 * {@link JumpableGenerator#jump() jump}() method exactly once, and then 1411 * parcel out generators from the resulting stream, one to each thread. 1412 * However, each generator produced also has type 1413 * {@link ArbitrarilyJumpableGenerator}; with care, different jump distances 1414 * can be used to traverse the entire state cycle in various ways. 1415 * 1416 * <p> Objects that implement {@link ArbitrarilyJumpableGenerator} are 1417 * typically not cryptographically secure. Consider instead using 1418 * {@link SecureRandom} to get a cryptographically secure pseudo-random 1419 * number generator for use by security-sensitive applications. 1420 */ 1421 interface ArbitrarilyJumpableGenerator extends LeapableGenerator { 1422 1423 /** 1424 * Returns an instance of {@link ArbitrarilyJumpableGenerator} that 1425 * utilizes the {@code name} <a href="package-summary.html#algorithms">algorithm</a>. 1426 * 1427 * @param name Name of random number generator 1428 * <a href="package-summary.html#algorithms">algorithm</a> 1429 * 1430 * @return An instance of {@link ArbitrarilyJumpableGenerator} 1431 * 1432 * @throws NullPointerException if name is null 1433 * @throws IllegalArgumentException if the named algorithm is not found 1434 */ of(String name)1435 static ArbitrarilyJumpableGenerator of(String name) { 1436 Objects.requireNonNull(name); 1437 1438 return RandomGeneratorFactory.of(name, ArbitrarilyJumpableGenerator.class); 1439 } 1440 1441 /** 1442 * Returns a new generator whose internal state is an exact copy of this 1443 * generator (therefore their future behavior should be identical if 1444 * subjected to the same series of operations). 1445 * 1446 * @return a new object that is a copy of this generator 1447 */ copy()1448 ArbitrarilyJumpableGenerator copy(); 1449 1450 /** 1451 * Alter the state of this pseudorandom number generator so as to jump 1452 * forward a distance equal to 2<sup>{@code logDistance}</sup> within 1453 * its state cycle. 1454 * 1455 * @param logDistance the base-2 logarithm of the distance to jump forward within the state 1456 * cycle 1457 * 1458 * @throws IllegalArgumentException if {@code logDistance} is 1459 * 2<sup>{@code logDistance}</sup> is 1460 * greater than the period of this generator 1461 */ jumpPowerOfTwo(int logDistance)1462 void jumpPowerOfTwo(int logDistance); 1463 1464 /** 1465 * Alter the state of this pseudorandom number generator so as to jump 1466 * forward a specified distance within its state cycle. 1467 * 1468 * @param distance the distance to jump forward within the state cycle 1469 * 1470 * @throws IllegalArgumentException if {@code distance} is not greater than 1471 * or equal to 0.0, or is greater than the 1472 * period of this generator 1473 */ jump(double distance)1474 void jump(double distance); 1475 1476 /** 1477 * Alter the state of this pseudorandom number generator so as to jump 1478 * forward a large, fixed distance (typically 2<sup>64</sup> or more) 1479 * within its state cycle. The distance used is that returned by method 1480 * {@link ArbitrarilyJumpableGenerator#jumpDistance() jumpDistance}(). 1481 * 1482 * @implSpec The default implementation invokes jump(jumpDistance()). 1483 */ jump()1484 default void jump() { jump(jumpDistance()); } 1485 1486 /** 1487 * Returns an effectively unlimited stream of new pseudorandom number 1488 * generators, each of which implements the 1489 * {@link ArbitrarilyJumpableGenerator} interface, produced by jumping 1490 * copies of this generator by different integer multiples of the 1491 * specified jump distance. 1492 * 1493 * @param distance a distance to jump forward within the state cycle 1494 * 1495 * @return a stream of objects that implement the {@link RandomGenerator} interface 1496 * 1497 * @throws IllegalArgumentException if {@code distance} is not greater than 1498 * or equal to 0.0, or is greater than the 1499 * period of this generator 1500 * 1501 * @implSpec The default implementation is equivalent to 1502 * {@link ArbitrarilyJumpableGenerator#jumps(long) jumps} 1503 * ({@link Long#MAX_VALUE Long.MAX_VALUE}). 1504 */ jumps(double distance)1505 default Stream<ArbitrarilyJumpableGenerator> jumps(double distance) { 1506 return Stream.generate(() -> copyAndJump(distance)).sequential(); 1507 } 1508 1509 /** 1510 * Returns a stream producing the given {@code streamSize} number of new 1511 * pseudorandom number generators, each of which implements the 1512 * {@link ArbitrarilyJumpableGenerator} interface, produced by jumping 1513 * copies of this generator by different integer multiples of the 1514 * specified jump distance. 1515 * 1516 * @param streamSize the number of generators to generate 1517 * @param distance a distance to jump forward within the state cycle 1518 * 1519 * @return a stream of objects that implement the {@link RandomGenerator} interface 1520 * 1521 * @throws IllegalArgumentException if {@code streamSize} is less than zero or if 1522 * {@code distance} is not greater than 1523 * or equal to 0.0, or is greater than the 1524 * period of this generator 1525 * 1526 * @implSpec The default implementation is equivalent to 1527 * jumps(distance).limit(streamSize). 1528 */ jumps(long streamSize, double distance)1529 default Stream<ArbitrarilyJumpableGenerator> jumps(long streamSize, double distance) { 1530 return jumps(distance).limit(streamSize); 1531 } 1532 1533 /** 1534 * Alter the state of this pseudorandom number generator so as to jump 1535 * forward a very large, fixed distance (typically 2<sup>128</sup> or 1536 * more) within its state cycle. The distance used is that returned by 1537 * method 1538 * {@link ArbitrarilyJumpableGenerator#leapDistance() leapDistance}(). 1539 */ leap()1540 default void leap() { jump(leapDistance()); } 1541 1542 /** 1543 * Copy this generator, jump this generator forward, then return the 1544 * copy. 1545 * 1546 * @param distance a distance to jump forward within the state cycle 1547 * 1548 * @return a copy of this generator object before the jump occurred 1549 * 1550 * @throws IllegalArgumentException if {@code distance} is not greater than 1551 * or equal to 0.0, or is greater than the 1552 * period of this generator 1553 * 1554 * @implSpec The default implementation copies this, jumps(distance) and then 1555 * returns the copy. 1556 */ copyAndJump(double distance)1557 default ArbitrarilyJumpableGenerator copyAndJump(double distance) { 1558 ArbitrarilyJumpableGenerator result = copy(); 1559 jump(distance); 1560 1561 return result; 1562 } 1563 1564 } 1565 } 1566