random: Random vs ThreadLocalRandom vs SecureRandom vs RandomGenerator module (seeds and a 2-output predictor, ranges and measured modulo bias, ThreadLocalRandom limits, SecureRandom algorithms and setSeed behaviour, the 13 java.util.random algorithms with split/jump, indicative timings), 16 contract tests
Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b6F5pq1M5ni1bNw8gr
This commit is contained in:
@@ -0,0 +1,69 @@
|
||||
package com.ankurm.random;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Random;
|
||||
import java.util.SplittableRandom;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.random.RandomGenerator;
|
||||
import java.util.random.RandomGeneratorFactory;
|
||||
|
||||
/**
|
||||
* Indicative timings. This is a plain timing loop with a warm-up, NOT a JMH benchmark: use the
|
||||
* ratios, not the absolute numbers, and expect them to move between runs and machines.
|
||||
*/
|
||||
public class BenchmarkDemo {
|
||||
private static final int SINGLE_CALLS = 20_000_000;
|
||||
private static final int THREADS = 4;
|
||||
private static final int CALLS_PER_THREAD = 5_000_000;
|
||||
|
||||
static volatile long sink;
|
||||
|
||||
interface IntSource { int next(); }
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
System.out.println("cores available: " + Runtime.getRuntime().availableProcessors());
|
||||
|
||||
Util.section("One thread: nanoseconds per nextInt(), " + SINGLE_CALLS + " calls");
|
||||
single("Random", new Random()::nextInt);
|
||||
single("SplittableRandom", new SplittableRandom()::nextInt);
|
||||
single("ThreadLocalRandom", () -> ThreadLocalRandom.current().nextInt());
|
||||
single("L32X64MixRandom (default)", RandomGenerator.getDefault()::nextInt);
|
||||
single("Xoshiro256PlusPlus", RandomGeneratorFactory.of("Xoshiro256PlusPlus").create()::nextInt);
|
||||
single("SecureRandom", new SecureRandom()::nextInt);
|
||||
|
||||
Util.section(THREADS + " threads sharing ONE instance, " + CALLS_PER_THREAD + " calls each (wall time, ms)");
|
||||
shared("Random (shared)", new Random()::nextInt);
|
||||
shared("SecureRandom (shared)", new SecureRandom()::nextInt);
|
||||
shared("ThreadLocalRandom.current()", () -> ThreadLocalRandom.current().nextInt());
|
||||
System.out.println("checksum (ignore): " + sink);
|
||||
}
|
||||
|
||||
private static void single(String name, IntSource s) {
|
||||
run(s, 2_000_000); // warm-up
|
||||
long t0 = System.nanoTime();
|
||||
long acc = run(s, SINGLE_CALLS);
|
||||
long t1 = System.nanoTime();
|
||||
sink += acc;
|
||||
System.out.printf("%-28s %7.1f ns/op%n", name, (double) (t1 - t0) / SINGLE_CALLS);
|
||||
}
|
||||
|
||||
private static long run(IntSource s, int n) {
|
||||
long acc = 0;
|
||||
for (int i = 0; i < n; i++) acc += s.next();
|
||||
return acc;
|
||||
}
|
||||
|
||||
private static void shared(String name, IntSource s) throws Exception {
|
||||
run(s, 500_000);
|
||||
Thread[] ts = new Thread[THREADS];
|
||||
long t0 = System.nanoTime();
|
||||
for (int i = 0; i < THREADS; i++) {
|
||||
ts[i] = new Thread(() -> sink += run(s, CALLS_PER_THREAD));
|
||||
ts[i].start();
|
||||
}
|
||||
for (Thread t : ts) t.join();
|
||||
long t1 = System.nanoTime();
|
||||
System.out.printf("%-28s %7.0f ms%n", name, (t1 - t0) / 1e6);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.ankurm.random;
|
||||
|
||||
/**
|
||||
* Shows why java.util.Random must never produce secrets.
|
||||
*
|
||||
* Random is a 48-bit linear congruential generator. nextInt() returns the top 32 bits of the
|
||||
* state, so one output hides only 16 bits. Two consecutive outputs leave 65,536 candidates for
|
||||
* the hidden bits, and the second output rules out all but one of them.
|
||||
*/
|
||||
final class Predictor {
|
||||
private static final long MULT = 0x5DEECE66DL;
|
||||
private static final long ADD = 0xBL;
|
||||
private static final long MASK = (1L << 48) - 1;
|
||||
|
||||
private Predictor() {}
|
||||
|
||||
private static long step(long state) {
|
||||
return (state * MULT + ADD) & MASK;
|
||||
}
|
||||
|
||||
/** Given two consecutive nextInt() results, returns the third one. */
|
||||
static int predictThird(int first, int second) {
|
||||
for (long low = 0; low < (1L << 16); low++) {
|
||||
long state1 = ((first & 0xFFFFFFFFL) << 16) | low;
|
||||
long state2 = step(state1);
|
||||
if ((int) (state2 >>> 16) == second) {
|
||||
return (int) (step(state2) >>> 16);
|
||||
}
|
||||
}
|
||||
throw new IllegalStateException("no matching state: not a java.util.Random sequence");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.ankurm.random;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Random;
|
||||
import java.util.SplittableRandom;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.random.RandomGenerator;
|
||||
import java.util.random.RandomGenerator.JumpableGenerator;
|
||||
import java.util.random.RandomGenerator.SplittableGenerator;
|
||||
import java.util.random.RandomGeneratorFactory;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
/** The java.util.random package (JEP 356): the interface, the default, the algorithm catalogue. */
|
||||
public class RandomGeneratorDemo {
|
||||
/** Written against the interface, so it works with any generator. */
|
||||
static int rollDie(RandomGenerator g) {
|
||||
return g.nextInt(1, 7);
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
Util.section("The old classes already implement RandomGenerator");
|
||||
RandomGenerator[] old = { new Random(), new SecureRandom(), new SplittableRandom(), ThreadLocalRandom.current() };
|
||||
for (RandomGenerator g : old) {
|
||||
int die = rollDie(g);
|
||||
System.out.println(g.getClass().getSimpleName() + " -> rollDie in 1..6: " + (die >= 1 && die <= 6));
|
||||
}
|
||||
|
||||
Util.section("The default generator");
|
||||
System.out.println("RandomGenerator.getDefault() : " + RandomGenerator.getDefault().getClass().getName());
|
||||
System.out.println("RandomGeneratorFactory.getDefault() : " + RandomGeneratorFactory.getDefault().name());
|
||||
|
||||
Util.section("Every algorithm this JDK ships (name, group, state bits, jumpable, splittable)");
|
||||
RandomGeneratorFactory.all()
|
||||
.sorted((p, q) -> p.name().compareTo(q.name()))
|
||||
.forEach(f -> System.out.printf("%-22s %-10s %5d bits jumpable=%-5b splittable=%b%n",
|
||||
f.name(), f.group(), f.stateBits(), f.isJumpable(), f.isSplittable()));
|
||||
|
||||
Util.section("Pick an algorithm by name, and seed it");
|
||||
RandomGenerator g1 = RandomGeneratorFactory.of("Xoshiro256PlusPlus").create(42L);
|
||||
RandomGenerator g2 = RandomGeneratorFactory.of("Xoshiro256PlusPlus").create(42L);
|
||||
System.out.println("Xoshiro256PlusPlus seed 42 #1: " + g1.nextInt(1000) + " " + g1.nextInt(1000) + " " + g1.nextInt(1000));
|
||||
System.out.println("Xoshiro256PlusPlus seed 42 #2: " + g2.nextInt(1000) + " " + g2.nextInt(1000) + " " + g2.nextInt(1000));
|
||||
RandomGenerator l = RandomGenerator.of("L64X128MixRandom");
|
||||
System.out.println("RandomGenerator.of(\"L64X128MixRandom\") -> " + l.getClass().getSimpleName());
|
||||
|
||||
Util.section("Splittable: independent generators for parallel work");
|
||||
SplittableGenerator root = RandomGeneratorFactory.<SplittableGenerator>of("L64X128MixRandom").create(42L);
|
||||
String firsts = IntStream.range(0, 4)
|
||||
.mapToObj(i -> String.valueOf(root.split().nextInt(1000)))
|
||||
.collect(Collectors.joining(" "));
|
||||
System.out.println("first draw of 4 split children: " + firsts);
|
||||
|
||||
Util.section("Jumpable: provably non-overlapping streams");
|
||||
JumpableGenerator j = RandomGeneratorFactory.<JumpableGenerator>of("Xoshiro256PlusPlus").create(42L);
|
||||
System.out.println("jump distance : " + j.jumpDistance());
|
||||
System.out.println("leap distance : " + ((RandomGenerator.LeapableGenerator) j).leapDistance());
|
||||
JumpableGenerator copy = j.copy();
|
||||
copy.jump();
|
||||
System.out.println("original next: " + j.nextInt(1000));
|
||||
System.out.println("after jump next: " + copy.nextInt(1000));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.ankurm.random;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Random;
|
||||
|
||||
/** Getting a number in a range: the right calls, and the classic wrong ones. */
|
||||
public class RangeDemo {
|
||||
public static void main(String[] args) {
|
||||
Random r = new Random(1);
|
||||
|
||||
Util.section("The right calls (upper bound is always exclusive)");
|
||||
System.out.println("nextInt(10) 0..9 : " + r.nextInt(10));
|
||||
System.out.println("nextInt(1, 7) 1..6 : " + r.nextInt(1, 7));
|
||||
System.out.println("nextInt(-5, 6) -5..5 : " + r.nextInt(-5, 6));
|
||||
System.out.println("nextDouble() [0,1) : " + r.nextDouble());
|
||||
System.out.println("nextDouble(2, 3) [2,3) : " + r.nextDouble(2, 3));
|
||||
System.out.println("ints(5, 1, 7) : " + Arrays.toString(r.ints(5, 1, 7).toArray()));
|
||||
|
||||
Util.section("Bad arguments fail loudly");
|
||||
try { r.nextInt(0); } catch (IllegalArgumentException e) { System.out.println("nextInt(0) -> " + e.getMessage()); }
|
||||
try { r.nextInt(5, 5); } catch (IllegalArgumentException e) { System.out.println("nextInt(5, 5) -> " + e.getMessage()); }
|
||||
|
||||
Util.section("Trap 1: nextInt() % n can be negative");
|
||||
Random t = new Random(2);
|
||||
int negatives = 0;
|
||||
for (int i = 0; i < 1000; i++) {
|
||||
if (t.nextInt() % 6 < 0) negatives++;
|
||||
}
|
||||
System.out.println("1000 draws of nextInt() % 6, negative results: " + negatives);
|
||||
|
||||
Util.section("Trap 2: Math.abs(Integer.MIN_VALUE) is still negative");
|
||||
System.out.println("Math.abs(Integer.MIN_VALUE) = " + Math.abs(Integer.MIN_VALUE));
|
||||
System.out.println("Math.abs(Integer.MIN_VALUE) % 10 = " + (Math.abs(Integer.MIN_VALUE) % 10));
|
||||
System.out.println("(nextInt() hits MIN_VALUE once in 2^32 calls, so tests never catch it)");
|
||||
|
||||
Util.section("Trap 3: modulo bias");
|
||||
int[] counts = new int[3];
|
||||
for (int v = 0; v < 8; v++) counts[v % 3]++;
|
||||
System.out.println("3 random bits (0..7) % 3 -> counts of 0,1,2: " + Arrays.toString(counts));
|
||||
|
||||
int bound = 1_500_000_000;
|
||||
int low = Integer.MAX_VALUE - bound + 1; // values below this are hit twice by (x % bound)
|
||||
double uniformShare = (double) low / bound;
|
||||
int draws = 2_000_000;
|
||||
Random m = new Random(3);
|
||||
int biasedLow = 0, fairLow = 0;
|
||||
for (int i = 0; i < draws; i++) {
|
||||
if ((m.nextInt() >>> 1) % bound < low) biasedLow++;
|
||||
if (m.nextInt(bound) < low) fairLow++;
|
||||
}
|
||||
System.out.printf("bound = %,d, results below %,d%n", bound, low);
|
||||
System.out.printf("expected share if uniform : %.4f%n", uniformShare);
|
||||
System.out.printf("(nextInt() >>> 1) %% bound : %.4f%n", (double) biasedLow / draws);
|
||||
System.out.printf("nextInt(bound) : %.4f%n", (double) fairLow / draws);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package com.ankurm.random;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.security.Security;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.TreeSet;
|
||||
|
||||
/** SecureRandom: which algorithm you really get, tokens, and what seeding does (and does not) do. */
|
||||
public class SecureRandomDemo {
|
||||
public static void main(String[] args) throws Exception {
|
||||
Util.section("What new SecureRandom() gives you on this machine");
|
||||
SecureRandom sr = new SecureRandom();
|
||||
System.out.println("algorithm : " + sr.getAlgorithm());
|
||||
System.out.println("provider : " + sr.getProvider().getName());
|
||||
|
||||
Util.section("getInstanceStrong()");
|
||||
SecureRandom strong = SecureRandom.getInstanceStrong();
|
||||
System.out.println("algorithm : " + strong.getAlgorithm());
|
||||
System.out.println("securerandom.strongAlgorithms = " + Security.getProperty("securerandom.strongAlgorithms"));
|
||||
|
||||
Util.section("SecureRandom algorithms registered in this JDK");
|
||||
TreeSet<String> names = new TreeSet<>();
|
||||
for (var p : Security.getProviders()) {
|
||||
for (var s : p.getServices()) {
|
||||
if (s.getType().equals("SecureRandom")) names.add(s.getAlgorithm() + " (" + p.getName() + ")");
|
||||
}
|
||||
}
|
||||
names.forEach(n -> System.out.println(" " + n));
|
||||
|
||||
Util.section("A session token: 32 random bytes = 256 bits");
|
||||
byte[] bytes = new byte[32];
|
||||
sr.nextBytes(bytes);
|
||||
String token = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
|
||||
System.out.println("length in characters: " + token.length() + " (value differs on every run)");
|
||||
|
||||
Util.section("Seeding: SHA1PRNG is deterministic, the default is not");
|
||||
SecureRandom s1 = SecureRandom.getInstance("SHA1PRNG");
|
||||
SecureRandom s2 = SecureRandom.getInstance("SHA1PRNG");
|
||||
s1.setSeed(42L);
|
||||
s2.setSeed(42L);
|
||||
byte[] x = new byte[8], y = new byte[8];
|
||||
s1.nextBytes(x);
|
||||
s2.nextBytes(y);
|
||||
System.out.println("SHA1PRNG, same seed, same bytes: " + Arrays.equals(x, y));
|
||||
|
||||
SecureRandom d1 = new SecureRandom();
|
||||
SecureRandom d2 = new SecureRandom();
|
||||
d1.setSeed(42L);
|
||||
d2.setSeed(42L);
|
||||
d1.nextBytes(x);
|
||||
d2.nextBytes(y);
|
||||
System.out.println(sr.getAlgorithm() + ", same seed, same bytes: " + Arrays.equals(x, y)
|
||||
+ " (setSeed only adds entropy; it does not make the output repeatable)");
|
||||
|
||||
Util.section("It is also a RandomGenerator, so the range methods work");
|
||||
System.out.println("nextInt(1, 7) in 1..6: " + (sr.nextInt(1, 7) >= 1));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.ankurm.random;
|
||||
|
||||
import java.util.Random;
|
||||
|
||||
/** What a seed is, what it gives you, and why java.util.Random is predictable. */
|
||||
public class SeedDemo {
|
||||
public static void main(String[] args) {
|
||||
Util.section("Same seed, same sequence");
|
||||
Random a = new Random(42);
|
||||
Random b = new Random(42);
|
||||
System.out.println("Random(42) #1: " + a.nextInt(100) + " " + a.nextInt(100) + " " + a.nextInt(100) + " " + a.nextInt(100) + " " + a.nextInt(100));
|
||||
System.out.println("Random(42) #2: " + b.nextInt(100) + " " + b.nextInt(100) + " " + b.nextInt(100) + " " + b.nextInt(100) + " " + b.nextInt(100));
|
||||
|
||||
Util.section("No seed: every instance starts somewhere different");
|
||||
Random c = new Random();
|
||||
Random d = new Random();
|
||||
System.out.println("new Random() #1: " + c.nextInt(100) + " " + c.nextInt(100) + " " + c.nextInt(100));
|
||||
System.out.println("new Random() #2: " + d.nextInt(100) + " " + d.nextInt(100) + " " + d.nextInt(100));
|
||||
System.out.println("(these two lines differ on every run)");
|
||||
|
||||
Util.section("setSeed rewinds an existing instance");
|
||||
Random e = new Random(7);
|
||||
int first = e.nextInt(1000);
|
||||
e.nextInt(1000);
|
||||
e.setSeed(7);
|
||||
System.out.println("first draw before setSeed(7): " + first + ", first draw after: " + e.nextInt(1000));
|
||||
|
||||
Util.section("Two outputs of an unseeded Random predict the third");
|
||||
Random victim = new Random();
|
||||
int o1 = victim.nextInt();
|
||||
int o2 = victim.nextInt();
|
||||
int predicted = Predictor.predictThird(o1, o2);
|
||||
int actual = victim.nextInt();
|
||||
System.out.println("seen output 1 : " + o1);
|
||||
System.out.println("seen output 2 : " + o2);
|
||||
System.out.println("predicted 3 : " + predicted);
|
||||
System.out.println("actual 3 : " + actual);
|
||||
System.out.println("prediction correct: " + (predicted == actual));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.ankurm.random;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
|
||||
/** ThreadLocalRandom: how to call it, what it refuses to do, and that threads get different streams. */
|
||||
public class ThreadLocalDemo {
|
||||
public static void main(String[] args) throws Exception {
|
||||
Util.section("The one correct way to call it");
|
||||
System.out.println("ThreadLocalRandom.current().nextInt(1, 7) -> in 1..6: "
|
||||
+ inRange(ThreadLocalRandom.current().nextInt(1, 7), 1, 6));
|
||||
|
||||
Util.section("It cannot be seeded");
|
||||
try {
|
||||
ThreadLocalRandom.current().setSeed(42);
|
||||
} catch (UnsupportedOperationException e) {
|
||||
System.out.println("setSeed(42) -> UnsupportedOperationException, message: " + e.getMessage());
|
||||
}
|
||||
|
||||
Util.section("Each thread has its own state");
|
||||
Set<Long> firstValues = new HashSet<>();
|
||||
Thread[] threads = new Thread[4];
|
||||
long[] results = new long[4];
|
||||
for (int i = 0; i < threads.length; i++) {
|
||||
int slot = i;
|
||||
threads[i] = new Thread(() -> results[slot] = ThreadLocalRandom.current().nextLong());
|
||||
threads[i].start();
|
||||
}
|
||||
for (Thread t : threads) t.join();
|
||||
for (long v : results) firstValues.add(v);
|
||||
System.out.println("4 threads, distinct first values: " + firstValues.size() + " of 4");
|
||||
|
||||
Util.section("Works the same on virtual threads");
|
||||
long[] vt = new long[1];
|
||||
Thread.ofVirtual().start(() -> vt[0] = ThreadLocalRandom.current().nextInt(1, 7)).join();
|
||||
System.out.println("virtual thread rolled a die: " + inRange((int) vt[0], 1, 6));
|
||||
}
|
||||
|
||||
private static boolean inRange(int v, int lo, int hi) {
|
||||
return v >= lo && v <= hi;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.ankurm.random;
|
||||
|
||||
/** Tiny printing helper shared by the demos. */
|
||||
final class Util {
|
||||
private Util() {}
|
||||
|
||||
static void section(String title) {
|
||||
System.out.println();
|
||||
System.out.println("== " + title + " ==");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package com.ankurm.random;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.junit.jupiter.api.Assumptions.assumeTrue;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Arrays;
|
||||
import java.util.Random;
|
||||
import java.util.SplittableRandom;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.random.RandomGenerator;
|
||||
import java.util.random.RandomGeneratorFactory;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** Pins every claim the post makes about the four APIs. */
|
||||
class RandomContractTest {
|
||||
|
||||
@Test
|
||||
void sameSeedGivesSameSequence() {
|
||||
Random a = new Random(42), b = new Random(42);
|
||||
for (int i = 0; i < 100; i++) assertEquals(a.nextInt(100), b.nextInt(100));
|
||||
}
|
||||
|
||||
@Test
|
||||
void firstThreeDrawsForSeed42AreStable() {
|
||||
Random r = new Random(42);
|
||||
assertArrayEquals(new int[] {30, 63, 48}, new int[] {r.nextInt(100), r.nextInt(100), r.nextInt(100)});
|
||||
}
|
||||
|
||||
@Test
|
||||
void setSeedRewinds() {
|
||||
Random r = new Random(7);
|
||||
int first = r.nextInt(1000);
|
||||
r.nextInt(1000);
|
||||
r.setSeed(7);
|
||||
assertEquals(first, r.nextInt(1000));
|
||||
}
|
||||
|
||||
@Test
|
||||
void twoOutputsPredictTheThirdForJavaUtilRandom() {
|
||||
for (int i = 0; i < 20; i++) {
|
||||
Random victim = new Random();
|
||||
int o1 = victim.nextInt(), o2 = victim.nextInt();
|
||||
assertEquals(victim.nextInt(), Predictor.predictThird(o1, o2));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void predictorCannotPredictSecureRandom() {
|
||||
SecureRandom sr = new SecureRandom();
|
||||
int wrong = 0;
|
||||
for (int i = 0; i < 20; i++) {
|
||||
int o1 = sr.nextInt(), o2 = sr.nextInt(), o3 = sr.nextInt();
|
||||
try {
|
||||
if (Predictor.predictThird(o1, o2) != o3) wrong++;
|
||||
} catch (IllegalStateException noMatch) {
|
||||
wrong++;
|
||||
}
|
||||
}
|
||||
assertEquals(20, wrong);
|
||||
}
|
||||
|
||||
@Test
|
||||
void nextIntModuloCanBeNegative() {
|
||||
Random r = new Random(2);
|
||||
boolean sawNegative = false;
|
||||
for (int i = 0; i < 1000; i++) sawNegative |= r.nextInt() % 6 < 0;
|
||||
assertTrue(sawNegative);
|
||||
}
|
||||
|
||||
@Test
|
||||
void absOfMinValueIsStillNegative() {
|
||||
assertEquals(Integer.MIN_VALUE, Math.abs(Integer.MIN_VALUE));
|
||||
assertTrue(Math.abs(Integer.MIN_VALUE) % 10 < 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void moduloIsBiasedAndNextIntBoundIsNot() {
|
||||
int bound = 1_500_000_000;
|
||||
int low = Integer.MAX_VALUE - bound + 1;
|
||||
double uniform = (double) low / bound;
|
||||
Random m = new Random(3);
|
||||
int draws = 1_000_000, biased = 0, fair = 0;
|
||||
for (int i = 0; i < draws; i++) {
|
||||
if ((m.nextInt() >>> 1) % bound < low) biased++;
|
||||
if (m.nextInt(bound) < low) fair++;
|
||||
}
|
||||
assertEquals(uniform, (double) fair / draws, 0.005);
|
||||
assertTrue((double) biased / draws > uniform + 0.15);
|
||||
}
|
||||
|
||||
@Test
|
||||
void rangeCallsRespectBounds() {
|
||||
Random r = new Random();
|
||||
for (int i = 0; i < 10_000; i++) {
|
||||
int v = r.nextInt(1, 7);
|
||||
assertTrue(v >= 1 && v <= 6);
|
||||
double d = r.nextDouble(2, 3);
|
||||
assertTrue(d >= 2 && d < 3);
|
||||
}
|
||||
assertThrows(IllegalArgumentException.class, () -> r.nextInt(0));
|
||||
assertThrows(IllegalArgumentException.class, () -> r.nextInt(5, 5));
|
||||
}
|
||||
|
||||
@Test
|
||||
void threadLocalRandomRefusesToBeSeeded() {
|
||||
assertThrows(UnsupportedOperationException.class, () -> ThreadLocalRandom.current().setSeed(42));
|
||||
}
|
||||
|
||||
@Test
|
||||
void secureRandomSetSeedDoesNotMakeNativePrngRepeatable() throws Exception {
|
||||
SecureRandom a = new SecureRandom(), b = new SecureRandom();
|
||||
assumeTrue(a.getAlgorithm().startsWith("NativePRNG"), "only meaningful where the default is NativePRNG");
|
||||
a.setSeed(42L);
|
||||
b.setSeed(42L);
|
||||
byte[] x = new byte[16], y = new byte[16];
|
||||
a.nextBytes(x);
|
||||
b.nextBytes(y);
|
||||
assertFalse(Arrays.equals(x, y));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sha1PrngIsRepeatableWhenSeededBeforeFirstUse() throws Exception {
|
||||
SecureRandom a = SecureRandom.getInstance("SHA1PRNG"), b = SecureRandom.getInstance("SHA1PRNG");
|
||||
a.setSeed(42L);
|
||||
b.setSeed(42L);
|
||||
byte[] x = new byte[16], y = new byte[16];
|
||||
a.nextBytes(x);
|
||||
b.nextBytes(y);
|
||||
assertArrayEquals(x, y);
|
||||
}
|
||||
|
||||
@Test
|
||||
void allFourClassicApisAreRandomGenerators() {
|
||||
RandomGenerator[] gs = { new Random(), new SecureRandom(), new SplittableRandom(), ThreadLocalRandom.current() };
|
||||
for (RandomGenerator g : gs) {
|
||||
int v = g.nextInt(1, 7);
|
||||
assertTrue(v >= 1 && v <= 6, g.getClass().getSimpleName());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void defaultGeneratorIsL32X64MixRandom() {
|
||||
assertEquals("L32X64MixRandom", RandomGeneratorFactory.getDefault().name());
|
||||
}
|
||||
|
||||
@Test
|
||||
void namedAlgorithmWithSameSeedRepeats() {
|
||||
RandomGenerator a = RandomGeneratorFactory.of("Xoshiro256PlusPlus").create(42L);
|
||||
RandomGenerator b = RandomGeneratorFactory.of("Xoshiro256PlusPlus").create(42L);
|
||||
for (int i = 0; i < 100; i++) assertEquals(a.nextLong(), b.nextLong());
|
||||
}
|
||||
|
||||
@Test
|
||||
void catalogueContainsTheExpectedFamilies() {
|
||||
var names = RandomGeneratorFactory.all().map(RandomGeneratorFactory::name).toList();
|
||||
assertTrue(names.containsAll(java.util.List.of("Random", "SecureRandom", "SplittableRandom",
|
||||
"L64X128MixRandom", "Xoshiro256PlusPlus", "Xoroshiro128PlusPlus")));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user