#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Params {
pub m: usize,
pub u: i64,
pub v: i64,
}
impl Params {
pub fn paper(m: usize) -> Self {
assert!(m >= 1);
let b = paper_half_width(m);
Self::with_half_width(m, b as f64)
}
pub fn with_half_width(m: usize, b: f64) -> Self {
let mu = m as f64 / 2.0;
Params {
m,
u: (mu - b).floor() as i64,
v: (mu + b).ceil() as i64,
}
}
pub fn with_window(m: usize, u: i64, v: i64) -> Self {
assert!(u <= v);
Params { m, u, v }
}
pub fn degree(&self) -> usize {
(self.v - self.u) as usize
}
pub fn window_bites(&self) -> bool {
self.degree() < self.m
}
pub fn in_window(&self, c: i64) -> bool {
self.u <= c && c <= self.v
}
pub fn exception_fraction(&self) -> f64 {
let m = self.m as u32;
let ln2m = m as f64 * core::f64::consts::LN_2;
let mut out = 0f64;
let mut ln_binom = 0f64;
for c in 0..=m {
if !self.in_window(c as i64) {
out += (ln_binom - ln2m).exp();
}
if c < m {
ln_binom += ((m - c) as f64).ln() - ((c + 1) as f64).ln();
}
}
out
}
pub fn paper_hoeffding_bound(m: usize) -> f64 {
let b = paper_half_width(m) as f64;
2.0 * (-2.0 * b * b / m as f64).exp()
}
}
pub fn paper_r(m: usize) -> u32 {
let mut r = 0;
while (1usize << r) < 2 * m {
r += 1;
}
r
}
pub fn paper_half_width(m: usize) -> u64 {
let r = paper_r(m) as f64;
(2.0 * m as f64 * r).sqrt().ceil() as u64
}
pub fn paper_threshold_m() -> usize {
(1..).find(|&m| Params::paper(m).window_bites()).unwrap()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn small_m_window_covers_everything() {
let p = Params::paper(3);
assert_eq!((p.u, p.v), (-4, 7));
assert!(!p.window_bites());
assert_eq!(p.exception_fraction(), 0.0);
}
#[test]
fn hoeffding_bound_holds() {
for m in 1..400 {
let p = Params::paper(m);
assert!(p.exception_fraction() <= Params::paper_hoeffding_bound(m) + 1e-15);
assert!(Params::paper_hoeffding_bound(m) <= 1.0 / (2.0 * (m as f64).powi(3)) + 1e-15);
}
}
#[test]
fn threshold_exists() {
let t = paper_threshold_m();
assert!(Params::paper(t).window_bites());
assert!(!Params::paper(t - 1).window_bites());
}
}