Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds an inverse_cdf() specialization for Uniform #166

Closed
wants to merge 3 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions src/distribution/uniform.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,19 @@ impl ContinuousCDF<f64, f64> for Uniform {
}
}

/// 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
}
}

/// Calculates the survival function for the uniform
/// distribution at `x`
///
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
Loading