Skip to content

Commit

Permalink
Adds an inverse_cdf() specialization for Uniform
Browse files Browse the repository at this point in the history
  • Loading branch information
TonyRippy authored and YeungOnion committed Apr 28, 2024
1 parent ce40e3a commit 9e63ee4
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions src/distribution/uniform.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,19 @@ impl ContinuousCDF<f64, f64> for Uniform {
(self.max - x) / (self.max - self.min)
}
}

/// Finds the value of `x` where `F(p) = x`
fn inverse_cdf(&self, p: f64) -> f64 {
if !(0.0..=1.0).contains(&p) {
panic!("p must be in [0, 1], was {}", p);
} else if p == 0.0 {
self.min
} else if p == 1.0 {
self.max
} else {
(self.max - self.min) * p + self.min
}
}
}

impl Min<f64> for Uniform {
Expand Down Expand Up @@ -417,6 +430,21 @@ mod tests {
test_case(0.0, f64::INFINITY, 1.0, cdf(f64::INFINITY));
}

#[test]
fn test_inverse_cdf() {
let inverse_cdf = |arg: f64| move |x: Uniform| x.inverse_cdf(arg);
test_case(0.0, 0.0, 0.0, inverse_cdf(0.0));
test_case(0.0, 0.0, 0.0, inverse_cdf(1.0));
test_case(0.0, 0.1, 0.05, inverse_cdf(0.5));
test_case(0.0, 10.0, 5.0, inverse_cdf(0.5));
test_case(1.0, 10.0, 1.0, inverse_cdf(0.0));
test_case(1.0, 10.0, 4.0, inverse_cdf(1.0 / 3.0));
test_case(1.0, 10.0, 10.0, inverse_cdf(1.0));
test_case(f64::NEG_INFINITY, f64::INFINITY, f64::NEG_INFINITY, inverse_cdf(0.0));
test_case(0.0, f64::INFINITY, 0.0, inverse_cdf(0.0));
test_case(0.0, f64::INFINITY, f64::INFINITY, inverse_cdf(1.0));
}

#[test]
fn test_cdf_lower_bound() {
let cdf = |arg: f64| move |x: Uniform| x.cdf(arg);
Expand Down

0 comments on commit 9e63ee4

Please sign in to comment.