Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Java integer fix #110

Merged
merged 2 commits into from
Nov 3, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 19 additions & 7 deletions src/interop/java/DRandomUniform.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@
import java.lang.Thread;

public final class DRandomUniform {

private static final ThreadLocal<SecureRandom> RNG = ThreadLocal.withInitial(DRandomUniform::createSecureRandom);

private DRandomUniform() {} // Prevent instantiation

private static final SecureRandom createSecureRandom() {
Expand All @@ -17,9 +15,23 @@ private static final SecureRandom createSecureRandom() {
return rng;
}

public static BigInteger Uniform(BigInteger n) {
// `n.intValueExact` will throw an `ArithmeticException` if `n` does not fit in an `int`.
// see https://docs.oracle.com/javase/8/docs/api/java/math/BigInteger.html#intValueExact--
return BigInteger.valueOf(RNG.get().nextInt(n.intValueExact()));
/**
* Sample a uniform value using rejection sampling between [0, n).
*
* @param n an integer (must be >= 1)
* @return a uniform value between 0 and n-1
* @throws IllegalArgumentException if `n` is less than 1
*/
public static BigInteger Uniform(final BigInteger n) {
if (n.compareTo(BigInteger.ONE) < 0) {
throw new IllegalArgumentException("n must be positive");
}

BigInteger sampleValue;
do {
sampleValue = new BigInteger(n.bitLength(), RNG.get());
} while (sampleValue.compareTo(n) >= 0);

return sampleValue;
}
}
}