Skip to content
Merged
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
47 changes: 44 additions & 3 deletions src/distribution/internal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -418,9 +418,41 @@
assert!(sum <= 1.0 + 1e-10);
}

/// pdf should be derivative of cdf
fn check_derivative_of_cdf_is_pdf<D: ContinuousCDF<f64, f64> + Continuous<f64, f64>>(
dist: &D,
x_min: f64,
x_max: f64,
step: f64,
) {
const DELTA: f64 = 1e-12;
const DX: f64 = 2.0 * DELTA;
let mut prev_x = x_min;

loop {
let x = prev_x + step;
let x_ahead = x + DELTA;
let x_behind = x - DELTA;
let density = dist.pdf(x);

let d_cdf = dist.cdf(x_ahead) - dist.cdf(x_behind);

assert_almost_eq!(d_cdf, DX * density, 1e-11);

if x >= x_max {
break;
} else {
prev_x = x;
}
}
}

/// Does a series of checks that all continuous distributions must obey.
/// 99% of the probability mass should be between x_min and x_max.
pub fn check_continuous_distribution<D: ContinuousCDF<f64, f64> + Continuous<f64, f64>>(
/// 99% of the probability mass should be between x_min and x_max or the finite
/// difference of cdf should be near to the pdf for much of the support.
pub fn check_continuous_distribution<
D: ContinuousCDF<f64, f64> + Continuous<f64, f64> + std::panic::RefUnwindSafe,
>(
dist: &D,
x_min: f64,
x_max: f64,
Expand All @@ -432,7 +464,16 @@
assert_eq!(dist.cdf(f64::NEG_INFINITY), 0.0);
assert_eq!(dist.cdf(f64::INFINITY), 1.0);

check_integrate_pdf_is_cdf(dist, x_min, x_max, (x_max - x_min) / 100000.0);
if std::panic::catch_unwind(|| {
check_integrate_pdf_is_cdf(dist, x_min, x_max, (x_max - x_min) / 100000.0);
})
.or(std::panic::catch_unwind(|| {
check_derivative_of_cdf_is_pdf(dist, x_min, x_max, (x_max - x_min) / 100000.0);
}))
.is_err()
{
panic!("Integration of pdf doesn't equal cdf and derivative of cdf doesn't equal pdf!");

Check warning on line 475 in src/distribution/internal.rs

View check run for this annotation

Codecov / codecov/patch

src/distribution/internal.rs#L475

Added line #L475 was not covered by tests
}
}

/// Does a series of checks that all positive discrete distributions must
Expand Down