rust-random / rand

A Rust library for random number generation.
https://crates.io/crates/rand
Other
1.68k stars 430 forks source link

Fix infinite loop in Binomial distribution #1325

Closed benjamin-lieser closed 1 year ago

benjamin-lieser commented 1 year ago

See issue #1324

The solution is the same as in the GSL implementation. Just retry if you reach a certain number of iterations.

benjamin-lieser commented 1 year ago

My case takes 5 minutes of computing to get there. I guess you can come up with seeds where this happens quickly. Essentially a u very close to 1 is required.

vks commented 1 year ago

I guess you can come up with seeds where this happens quickly.

Yes, see my comment in #1324. I guess I could try to find a seed for the internal test::rng, too.

vks commented 1 year ago

This test hangs without this PR. Maybe you can add it?

#[test]
fn binomial_avoid_infinite_loop() {
    let dist = Binomial::new(16000000, 3.1444753148558566e-10).unwrap();
    let mut sum: u64 = 0;
    let mut rng = crate::test::rng(742);
    for _ in 0..100_000 {
        sum = sum.wrapping_add(dist.sample(&mut rng));
    }
    assert_ne!(sum, 0);
}
vks commented 1 year ago

Great, thanks!