Skip to content

Commit 0f3eced

Browse files
authored
Poisson distribution falls into an infinite loop for parameter λ=∞ (#1290) (#1291)
1 parent 17c8b26 commit 0f3eced

File tree

2 files changed

+16
-3
lines changed

2 files changed

+16
-3
lines changed

rand_distr/CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
99
This breaks serialization compatibility with older versions.
1010
- Upgrade Rand
1111
- Fix Knuth's method so `Poisson` doesn't return -1.0 for small lambda
12+
- Fix `Poisson` distribution instantiation so it return an error if lambda is infinite
1213

1314
## [0.4.3] - 2021-12-30
1415
- Fix `no_std` build (#1208)

rand_distr/src/poisson.rs

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -44,14 +44,17 @@ where F: Float + FloatConst, Standard: Distribution<F>
4444
/// Error type returned from `Poisson::new`.
4545
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
4646
pub enum Error {
47-
/// `lambda <= 0` or `nan`.
47+
/// `lambda <= 0`
4848
ShapeTooSmall,
49+
/// `lambda = ∞` or `lambda = nan`
50+
NonFinite,
4951
}
5052

5153
impl fmt::Display for Error {
5254
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5355
f.write_str(match self {
5456
Error::ShapeTooSmall => "lambda is not positive in Poisson distribution",
57+
Error::NonFinite => "lambda is infinite or nan in Poisson distribution",
5558
})
5659
}
5760
}
@@ -66,6 +69,9 @@ where F: Float + FloatConst, Standard: Distribution<F>
6669
/// Construct a new `Poisson` with the given shape parameter
6770
/// `lambda`.
6871
pub fn new(lambda: F) -> Result<Poisson<F>, Error> {
72+
if !lambda.is_finite() {
73+
return Err(Error::NonFinite);
74+
}
6975
if !(lambda > F::zero()) {
7076
return Err(Error::ShapeTooSmall);
7177
}
@@ -163,7 +169,7 @@ mod test {
163169
fn test_poisson_avg() {
164170
test_poisson_avg_gen::<f64>(10.0, 0.1);
165171
test_poisson_avg_gen::<f64>(15.0, 0.1);
166-
172+
167173
test_poisson_avg_gen::<f32>(10.0, 0.1);
168174
test_poisson_avg_gen::<f32>(15.0, 0.1);
169175

@@ -178,6 +184,12 @@ mod test {
178184
Poisson::new(0.0).unwrap();
179185
}
180186

187+
#[test]
188+
#[should_panic]
189+
fn test_poisson_invalid_lambda_infinity() {
190+
Poisson::new(f64::INFINITY).unwrap();
191+
}
192+
181193
#[test]
182194
#[should_panic]
183195
fn test_poisson_invalid_lambda_neg() {
@@ -188,4 +200,4 @@ mod test {
188200
fn poisson_distributions_can_be_compared() {
189201
assert_eq!(Poisson::new(1.0), Poisson::new(1.0));
190202
}
191-
}
203+
}

0 commit comments

Comments
 (0)