Skip to content

Commit

Permalink
fix: mode for gamma distribution is 0 for shape<=1
Browse files Browse the repository at this point in the history
fix: return None for Gamma::mode when α < 1
  • Loading branch information
YeungOnion committed Apr 17, 2024
1 parent 892d388 commit c6dc2de
Showing 1 changed file with 17 additions and 14 deletions.
31 changes: 17 additions & 14 deletions src/distribution/gamma.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,17 +133,13 @@ impl ContinuousCDF<f64, f64> for Gamma {
fn sf(&self, x: f64) -> f64 {
if x <= 0.0 {
1.0
}
else if ulps_eq!(x, self.shape) && self.rate.is_infinite() {
} else if ulps_eq!(x, self.shape) && self.rate.is_infinite() {
0.0
}
else if self.rate.is_infinite() {
} else if self.rate.is_infinite() {
1.0
}
else if x.is_infinite() {
} else if x.is_infinite() {
0.0
}
else {
} else {
gamma::gamma_ur(self.shape, x * self.rate)
}
}
Expand Down Expand Up @@ -239,13 +235,17 @@ impl Mode<Option<f64>> for Gamma {
///
/// # Formula
///
/// ```ignore
/// (α - 1) / β
/// ```text
/// (α - 1) / β, where α > 1
/// ```
///
/// where `α` is the shape and `β` is the rate
fn mode(&self) -> Option<f64> {
Some((self.shape - 1.0) / self.rate)
if self.shape >= 1.0 {
Some((self.shape - 1.0) / self.rate)
} else {
None
}
}
}

Expand Down Expand Up @@ -353,6 +353,7 @@ pub fn sample_unchecked<R: Rng + ?Sized>(rng: &mut R, shape: f64, rate: f64) ->

#[cfg(all(test, feature = "nightly"))]
mod tests {

use super::*;
use crate::consts::ACC;
use crate::distribution::internal::*;
Expand Down Expand Up @@ -452,10 +453,12 @@ mod tests {

#[test]
fn test_mode() {
use rand::distributions::uniform::UniformFloat;
use rand::rngs;
let f = |x: Gamma| x.mode().unwrap();
let test = [((1.0, 0.1), 0.0), ((1.0, 1.0), 0.0)];
for &(arg, res) in test.iter() {
test_case_special(arg, res, 10e-6, f);
let test = [(1.0, 0.1), (1.0, 1.0)];
for &arg in test.iter() {
test_case_special(arg, 0.0, 10e-6, f);
}
let test = [((10.0, 10.0), 0.9), ((10.0, 1.0), 9.0), ((10.0, INF), 0.0)];
for &(arg, res) in test.iter() {
Expand Down

0 comments on commit c6dc2de

Please sign in to comment.