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.Assert;
26 import org.junit.Test;
27
28
29
30
31 public class JDKRandomBridgeTest {
32 @Test
33 public 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 Assert.assertNotEquals(seed, newSeed);
43 rng1.setSeed(newSeed);
44 rng2.setSeed(newSeed);
45 checkSameSequence(rng1, rng2);
46 }
47
48 @Test
49 public 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 ByteArrayOutputStream bos = new ByteArrayOutputStream();
58 ObjectOutputStream oos = new ObjectOutputStream(bos);
59 oos.writeObject(rng);
60
61
62 ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
63 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 Assert.assertEquals(rng1.nextInt(),
80 rng2.nextInt());
81 }
82 for (int i = 0; i < 7; i++) {
83 Assert.assertEquals(rng1.nextLong(),
84 rng2.nextLong());
85 }
86 for (int i = 0; i < 9; i++) {
87 Assert.assertEquals(rng1.nextFloat(),
88 rng2.nextFloat(),
89 0f);
90 }
91 for (int i = 0; i < 12; i++) {
92 Assert.assertEquals(rng1.nextDouble(),
93 rng2.nextDouble(),
94 0d);
95 }
96 for (int i = 0; i < 17; i++) {
97 Assert.assertEquals(rng1.nextGaussian(),
98 rng2.nextGaussian(),
99 0d);
100 }
101 for (int i = 0; i < 18; i++) {
102 Assert.assertEquals(rng1.nextBoolean(),
103 rng2.nextBoolean());
104 }
105 for (int i = 0; i < 19; i++) {
106 final int max = i + 123456;
107 Assert.assertEquals(rng1.nextInt(max),
108 rng2.nextInt(max));
109 }
110
111 final int len = 233;
112 final byte[] store1 = new byte[len];
113 final byte[] store2 = new byte[len];
114 rng1.nextBytes(store1);
115 rng2.nextBytes(store2);
116 for (int i = 0; i < len; i++) {
117 Assert.assertEquals(store1[i],
118 store2[i]);
119 }
120 }
121 }