Skip to content

Commit

Permalink
Poisson distribution falls into an infinite loop for parameter λ=∞ (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
Thopic committed Feb 24, 2023
1 parent 7c1e649 commit 6753673
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
1 change: 1 addition & 0 deletions rand_distr/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
This breaks serialization compatibility with older versions.
- Upgrade Rand
- Fix Knuth's method so `Poisson` doesn't return -1.0 for small lambda
- Fix `Poisson` distribution instantiation so it return an error if lambda is infinite

## [0.4.3] - 2021-12-30
- Fix `no_std` build (#1208)
Expand Down
16 changes: 14 additions & 2 deletions rand_distr/src/poisson.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,15 @@ where F: Float + FloatConst, Standard: Distribution<F>
pub enum Error {
/// `lambda <= 0` or `nan`.
ShapeTooSmall,
/// `lambda == +∞`
ParameterInfinite,
}

impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Error::ShapeTooSmall => "lambda is not positive in Poisson distribution",
Error::ParameterInfinite => "lambda is infinite in Poisson distribution",
})
}
}
Expand All @@ -69,6 +72,9 @@ where F: Float + FloatConst, Standard: Distribution<F>
if !(lambda > F::zero()) {
return Err(Error::ShapeTooSmall);
}
if lambda.is_infinite() {
return Err(Error::ParameterInfinite);
}
let log_lambda = lambda.ln();
Ok(Poisson {
lambda,
Expand Down Expand Up @@ -163,7 +169,7 @@ mod test {
fn test_poisson_avg() {
test_poisson_avg_gen::<f64>(10.0, 0.1);
test_poisson_avg_gen::<f64>(15.0, 0.1);

test_poisson_avg_gen::<f32>(10.0, 0.1);
test_poisson_avg_gen::<f32>(15.0, 0.1);

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

#[test]
#[should_panic]
fn test_poisson_invalid_lambda_infinity() {
Poisson::new(f64::INFINITY).unwrap();
}

#[test]
#[should_panic]
fn test_poisson_invalid_lambda_neg() {
Expand All @@ -188,4 +200,4 @@ mod test {
fn poisson_distributions_can_be_compared() {
assert_eq!(Poisson::new(1.0), Poisson::new(1.0));
}
}
}

0 comments on commit 6753673

Please sign in to comment.