1#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14pub struct Params {
15 pub m: usize,
17 pub u: i64,
19 pub v: i64,
21}
22
23impl Params {
24 pub fn paper(m: usize) -> Self {
26 assert!(m >= 1);
27 let b = paper_half_width(m);
28 Self::with_half_width(m, b as f64)
29 }
30
31 pub fn with_half_width(m: usize, b: f64) -> Self {
37 let mu = m as f64 / 2.0;
38 Params {
39 m,
40 u: (mu - b).floor() as i64,
41 v: (mu + b).ceil() as i64,
42 }
43 }
44
45 pub fn with_window(m: usize, u: i64, v: i64) -> Self {
47 assert!(u <= v);
48 Params { m, u, v }
49 }
50
51 pub fn degree(&self) -> usize {
53 (self.v - self.u) as usize
54 }
55
56 pub fn window_bites(&self) -> bool {
59 self.degree() < self.m
60 }
61
62 pub fn in_window(&self, c: i64) -> bool {
64 self.u <= c && c <= self.v
65 }
66
67 pub fn exception_fraction(&self) -> f64 {
70 let m = self.m as u32;
72 let ln2m = m as f64 * core::f64::consts::LN_2;
73 let mut out = 0f64;
74 let mut ln_binom = 0f64;
75 for c in 0..=m {
76 if !self.in_window(c as i64) {
77 out += (ln_binom - ln2m).exp();
78 }
79 if c < m {
80 ln_binom += ((m - c) as f64).ln() - ((c + 1) as f64).ln();
81 }
82 }
83 out
84 }
85
86 pub fn paper_hoeffding_bound(m: usize) -> f64 {
89 let b = paper_half_width(m) as f64;
90 2.0 * (-2.0 * b * b / m as f64).exp()
91 }
92}
93
94pub fn paper_r(m: usize) -> u32 {
96 let mut r = 0;
97 while (1usize << r) < 2 * m {
98 r += 1;
99 }
100 r
101}
102
103pub fn paper_half_width(m: usize) -> u64 {
105 let r = paper_r(m) as f64;
106 (2.0 * m as f64 * r).sqrt().ceil() as u64
107}
108
109pub fn paper_threshold_m() -> usize {
111 (1..).find(|&m| Params::paper(m).window_bites()).unwrap()
112}
113
114#[cfg(test)]
115mod tests {
116 use super::*;
117
118 #[test]
119 fn small_m_window_covers_everything() {
120 let p = Params::paper(3);
122 assert_eq!((p.u, p.v), (-4, 7));
123 assert!(!p.window_bites());
124 assert_eq!(p.exception_fraction(), 0.0);
125 }
126
127 #[test]
128 fn hoeffding_bound_holds() {
129 for m in 1..400 {
130 let p = Params::paper(m);
131 assert!(p.exception_fraction() <= Params::paper_hoeffding_bound(m) + 1e-15);
132 assert!(Params::paper_hoeffding_bound(m) <= 1.0 / (2.0 * (m as f64).powi(3)) + 1e-15);
133 }
134 }
135
136 #[test]
137 fn threshold_exists() {
138 let t = paper_threshold_m();
139 assert!(Params::paper(t).window_bites());
140 assert!(!Params::paper(t - 1).window_bites());
141 }
142}