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

Fix infinite loop in Binomial distribution #1325

Merged
merged 4 commits into from
Jul 14, 2023
Merged
Changes from 1 commit
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
30 changes: 22 additions & 8 deletions rand_distr/src/binomial.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,20 +110,34 @@ impl Distribution<u64> for Binomial {
// Threshold for preferring the BINV algorithm. The paper suggests 10,
// Ranlib uses 30, and GSL uses 14.
const BINV_THRESHOLD: f64 = 10.;

//Same value as in GSL
//It is possible for BINV to get stuck, so we break if x > BINV_MAX_X and try again
//It would be safer to set BINV_MAX_X to self.n, but it is extremly unlikely to be relevant
//When n*p < 10, so is n*p*q which is the variance, so a result > 110 would be 100 / sqrt(10) = 31 standard deviations away
benjamin-lieser marked this conversation as resolved.
Show resolved Hide resolved
const BINV_MAX_X : u64 = 110;

if (self.n as f64) * p < BINV_THRESHOLD && self.n <= (core::i32::MAX as u64) {
// Use the BINV algorithm.
let s = p / q;
let a = ((self.n + 1) as f64) * s;
let mut r = q.powi(self.n as i32);
let mut u: f64 = rng.gen();
let mut x = 0;
while u > r as f64 {
u -= r;
x += 1;
r *= a / (x as f64) - s;

result = 'outer: loop {
let mut r = q.powi(self.n as i32);
let mut u: f64 = rng.gen();
let mut x = 0;

while u > r as f64 {
u -= r;
x += 1;
if x > BINV_MAX_X {
continue 'outer;
}
r *= a / (x as f64) - s;
}
break x;
benjamin-lieser marked this conversation as resolved.
Show resolved Hide resolved

}
result = x;
} else {
// Use the BTPE algorithm.

Expand Down