-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathUniformRNGUtils.java
79 lines (70 loc) · 2.52 KB
/
UniformRNGUtils.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package biz.k11i.rng;
import java.util.Random;
import java.util.SplittableRandom;
@SuppressWarnings("Duplicates")
public class UniformRNGUtils {
/**
* Returns a random integer sampled from discrete uniform distribution {@code unif{0, bound - 1}}.
*
* <p>
* This implementation uses "nearly divisionless" algorithm by Lemire.
* </p>
* <p>
* Lemire, Daniel.
* <i>"Fast random integer generation in an interval."</i>
* ACM Transactions on Modeling and Computer Simulation (TOMACS) 29.1 (2019): 3.
* </p>
*
* @param random random number generator ({@link Random} object)
* @param bound the upper bound (exclusive)
* @return sampled random integer between 0 (inclusive) and {@code bound} (exclusive)
*/
public static int nextInt(Random random, int bound) {
if (bound <= 0) {
throw new IllegalArgumentException("bound must be positive");
}
long x = ((long) random.nextInt()) & 0xffff_ffffL;
long m = x * bound;
long l = m & 0xffff_ffffL;
if (l < bound) {
for (long t = 0x1_0000_0000L % bound; l < t; ) {
x = ((long) random.nextInt()) & 0xffff_ffffL;
m = x * bound;
l = m & 0xffff_ffffL;
}
}
return (int) (m >>> 32);
}
/**
* Returns a random integer sampled from discrete uniform distribution {@code unif{0, bound - 1}}.
*
* <p>
* This implementation uses "nearly divisionless" algorithm by Lemire.
* </p>
* <p>
* Lemire, Daniel.
* <i>"Fast random integer generation in an interval."</i>
* ACM Transactions on Modeling and Computer Simulation (TOMACS) 29.1 (2019): 3.
* </p>
*
* @param random random number generator ({@link SplittableRandom} object)
* @param bound the upper bound (exclusive)
* @return sampled random integer between 0 (inclusive) and {@code bound} (exclusive)
*/
public static int nextInt(SplittableRandom random, int bound) {
if (bound <= 0) {
throw new IllegalArgumentException("bound must be positive");
}
long x = ((long) random.nextInt()) & 0xffff_ffffL;
long m = x * bound;
long l = m & 0xffff_ffffL;
if (l < bound) {
for (long t = 0x1_0000_0000L % bound; l < t; ) {
x = ((long) random.nextInt()) & 0xffff_ffffL;
m = x * bound;
l = m & 0xffff_ffffL;
}
}
return (int) (m >>> 32);
}
}