rust-random / rand

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

Binomial::sample panics with extreme parameters #1378

Closed TheIronBorn closed 1 month ago

TheIronBorn commented 10 months ago
let distr = Binomial::new(1 << 31, f64::MIN_POSITIVE).unwrap();
let x = thread_rng().sample(distr);
println!("{}", x);

panics with Uniform::new called with low >= high at: https://github.com/rust-random/rand/blob/1f4507a8e1cf8050e4ceef95eeda8f64645b6719/rand_distr/src/binomial.rs#L180

dhardy commented 9 months ago

A panic in sample is definitely a bug. Would you mind improving the constructor to check for this?

TheIronBorn commented 9 months ago

Working on it now

TheIronBorn commented 9 months ago

I can't find an easy relationship between n and p to make an easy check. Bounds on n * p produce false positives.

So we can:

TheIronBorn commented 9 months ago

I also found some panics in f64_to_i64 so there are multiple dimensions to consider

dhardy commented 8 months ago

Sorry for the delay — there's no obvious best approach here. With that said, I suggest:

This is all assuming that it is possible to find reasonable bounds on inputs with a low impact on real usage.

benjamin-lieser commented 3 months ago

One problem is that we enter the BTPE even when np < 10. This happens when n > i32::MAX

I don't know if there are more issues than this, but this could be prevented by rejecting this condition. Maybe we can also fix BINV for n > i32::MAX

BTPE needs this condition, otherwise you get a negative radius in p1