Skip to content

Commit 95bfe89

Browse files
committed
implement more methods for Xorshf64
1 parent 3242d5b commit 95bfe89

File tree

3 files changed

+33
-2
lines changed

3 files changed

+33
-2
lines changed

src/main/java/de/tilman_neumann/jml/random/Xorshf32b.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,8 +45,8 @@ public int nextInt() {
4545
*/
4646
public int nextInt(int max) {
4747
final long i = nextInt();
48-
final long l = i<0 ? -i : i; // up to unsigned 2^32 - 1
49-
final long prod = l * max; // up to max * (2^32 - 1)
48+
final long l = i<0 ? -i : i; // up to unsigned 2^31 - 1
49+
final long prod = l * max; // up to max * (2^31 - 1)
5050
return (int) (prod >>> 32);
5151
}
5252

src/main/java/de/tilman_neumann/jml/random/Xorshf64.java

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@
1313
*/
1414
package de.tilman_neumann.jml.random;
1515

16+
import de.tilman_neumann.jml.base.Uint128;
17+
1618
/**
1719
* <strong>Experimental</strong> 64 bit random number generator computing longs from three consecutive 32 bit random numbers.
1820
*
@@ -36,4 +38,19 @@ public long nextLong() {
3638
i2 = i3;
3739
return result;
3840
}
41+
42+
/**
43+
* @param max
44+
* @return a random long number N with 0 <= N <= max.
45+
*/
46+
public long nextLong(long max) {
47+
final long i = nextLong();
48+
final long l = i<0 ? -i : i; // up to unsigned 2^63 - 1
49+
final Uint128 prod = Uint128.mul64_MH(l, max);
50+
return prod.getHigh();
51+
}
52+
53+
public long nextLong(long min, long max) {
54+
return min + nextLong(max - min);
55+
}
3956
}

src/test/java/de/tilman_neumann/jml/random/RngPerformanceTest.java

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,5 +171,19 @@ public static void main(String[] args) {
171171
xorshf64.nextLong();
172172
}
173173
LOG.debug("Xorshf64.nextLong() took " + timer.capture() + " ms");
174+
175+
// test nextLong(long upper)
176+
long upperLong = 1L<<55;
177+
for (int i=0; i<NCOUNT; i++) {
178+
xorshf64.nextLong(upperLong);
179+
}
180+
LOG.debug("Xorshf64.nextLong(upper) took " + timer.capture() + " ms");
181+
182+
// test nextLong(long lower, long upper)
183+
long lowerLong = 1L<<20;
184+
for (int i=0; i<NCOUNT; i++) {
185+
xorshf64.nextLong(lowerLong, upperLong);
186+
}
187+
LOG.debug("Xorshf64.nextLong(lower, upper) took " + timer.capture() + " ms");
174188
}
175189
}

0 commit comments

Comments
 (0)