1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.rng.simple;
18
19 import java.io.IOException;
20 import java.io.ObjectOutputStream;
21 import java.io.ObjectInputStream;
22 import java.io.ByteArrayOutputStream;
23 import java.io.ByteArrayInputStream;
24 import java.util.Random;
25 import org.junit.jupiter.api.Assertions;
26 import org.junit.jupiter.api.Test;
27
28
29
30
31 class JDKRandomBridgeTest {
32 @Test
33 void testJDKRandomEquivalence() {
34
35 final long seed = RandomSource.createLong();
36 final Random rng1 = new Random(seed);
37 final Random rng2 = new JDKRandomBridge(RandomSource.JDK, seed);
38 checkSameSequence(rng1, rng2);
39
40
41 final long newSeed = RandomSource.createLong();
42 Assertions.assertNotEquals(seed, newSeed);
43 rng1.setSeed(newSeed);
44 rng2.setSeed(newSeed);
45 checkSameSequence(rng1, rng2);
46 }
47
48 @Test
49 void testSerialization()
50 throws IOException,
51 ClassNotFoundException {
52
53 final long seed = RandomSource.createLong();
54 final Random rng = new JDKRandomBridge(RandomSource.SPLIT_MIX_64, seed);
55
56
57 final ByteArrayOutputStream bos = new ByteArrayOutputStream();
58 final ObjectOutputStream oos = new ObjectOutputStream(bos);
59 oos.writeObject(rng);
60
61
62 final ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
63 final ObjectInputStream ois = new ObjectInputStream(bis);
64 final Random serialRng = (Random) (ois.readObject());
65
66
67 checkSameSequence(rng, serialRng);
68 }
69
70
71
72
73
74
75
76 private void checkSameSequence(Random rng1,
77 Random rng2) {
78 for (int i = 0; i < 4; i++) {
79 Assertions.assertEquals(rng1.nextInt(),
80 rng2.nextInt());
81 }
82 for (int i = 0; i < 7; i++) {
83 Assertions.assertEquals(rng1.nextLong(),
84 rng2.nextLong());
85 }
86 for (int i = 0; i < 9; i++) {
87 Assertions.assertEquals(rng1.nextFloat(),
88 rng2.nextFloat());
89 }
90 for (int i = 0; i < 12; i++) {
91 Assertions.assertEquals(rng1.nextDouble(),
92 rng2.nextDouble());
93 }
94 for (int i = 0; i < 17; i++) {
95 Assertions.assertEquals(rng1.nextGaussian(),
96 rng2.nextGaussian());
97 }
98 for (int i = 0; i < 18; i++) {
99 Assertions.assertEquals(rng1.nextBoolean(),
100 rng2.nextBoolean());
101 }
102 for (int i = 0; i < 19; i++) {
103 final int max = i + 123456;
104 Assertions.assertEquals(rng1.nextInt(max),
105 rng2.nextInt(max));
106 }
107
108 final int len = 233;
109 final byte[] store1 = new byte[len];
110 final byte[] store2 = new byte[len];
111 rng1.nextBytes(store1);
112 rng2.nextBytes(store2);
113 for (int i = 0; i < len; i++) {
114 Assertions.assertEquals(store1[i],
115 store2[i]);
116 }
117 }
118 }