Skip to main content

tpt_math_stats/
dist.rs

1#![forbid(unsafe_code)]
2//! Probability distributions used by the hypothesis tests, implemented in-house
3//! (no `statrs` / Apache-2.0 dependency).
4//!
5//! Each continuous distribution exposes [`ContinuousCDF`] so call sites that
6//! need a cumulative (`cdf`) or survival (`sf`) probability share one trait,
7//! mirroring the surface the rest of the crate was written against.
8
9/// Cumulative and survival probabilities of a continuous distribution.
10pub trait ContinuousCDF {
11    /// Cumulative distribution function `P(X <= x)`.
12    fn cdf(&self, x: f64) -> f64;
13    /// Survival function `P(X > x) = 1 - cdf(x)`.
14    fn sf(&self, x: f64) -> f64;
15}
16
17// ---------------------------------------------------------------------------
18// Chi-squared
19// ---------------------------------------------------------------------------
20
21/// A chi-squared distribution with `k` degrees of freedom.
22///
23/// `cdf(x) = P(k/2, x/2)` and `sf(x) = Q(k/2, x/2)`, the regularized
24/// incomplete gamma functions.
25#[derive(Debug)]
26pub struct ChiSquared {
27    /// Degrees of freedom (must be positive).
28    k: f64,
29}
30
31impl ChiSquared {
32    /// Construct a chi-squared distribution with `k` degrees of freedom.
33    ///
34    /// # Errors
35    ///
36    /// Returns an error string if `k <= 0`.
37    pub fn new(k: f64) -> Result<Self, &'static str> {
38        if k <= 0.0 {
39            return Err("degrees of freedom must be positive");
40        }
41        Ok(ChiSquared { k })
42    }
43}
44
45impl ContinuousCDF for ChiSquared {
46    fn cdf(&self, x: f64) -> f64 {
47        crate::special::gamma_p(self.k / 2.0, x / 2.0)
48    }
49
50    fn sf(&self, x: f64) -> f64 {
51        crate::special::gamma_q(self.k / 2.0, x / 2.0)
52    }
53}
54
55// ---------------------------------------------------------------------------
56// Student's t
57// ---------------------------------------------------------------------------
58
59/// Student's t-distribution with location `loc`, scale `scale`, and `df`
60/// degrees of freedom.
61///
62/// The survival/cumulative probabilities follow from the regularized incomplete
63/// beta: for the standardized value `u = (x - loc) / scale`,
64/// `sf(u) = 0.5 * I_{df/(df + u²)}(df/2, 1/2)`.
65#[derive(Debug)]
66pub struct StudentsT {
67    loc: f64,
68    scale: f64,
69    df: f64,
70}
71
72impl StudentsT {
73    /// Construct a Student's t-distribution with location `loc`, scale
74    /// `scale`, and `df` degrees of freedom.
75    ///
76    /// # Errors
77    ///
78    /// Returns an error string if `df <= 0` or `scale <= 0`.
79    pub fn new(loc: f64, scale: f64, df: f64) -> Result<Self, &'static str> {
80        if df <= 0.0 {
81            return Err("degrees of freedom must be positive");
82        }
83        if scale <= 0.0 {
84            return Err("scale must be positive");
85        }
86        Ok(StudentsT { loc, scale, df })
87    }
88}
89
90impl ContinuousCDF for StudentsT {
91    fn cdf(&self, x: f64) -> f64 {
92        let u = (x - self.loc) / self.scale;
93        let z = self.df / (self.df + u * u);
94        let ib = crate::special::beta_reg(self.df / 2.0, 0.5, z);
95        if u >= 0.0 {
96            1.0 - 0.5 * ib
97        } else {
98            0.5 * ib
99        }
100    }
101
102    fn sf(&self, x: f64) -> f64 {
103        // Evaluate the upper tail directly from the regularized incomplete beta
104        // rather than `1 - cdf(x)`: for large `|x|` the cdf rounds to 1.0 and
105        // `1 - cdf` annihilates the tiny, significant tail probability.
106        let u = (x - self.loc) / self.scale;
107        let z = self.df / (self.df + u * u);
108        let ib = crate::special::beta_reg(self.df / 2.0, 0.5, z);
109        if u >= 0.0 {
110            0.5 * ib
111        } else {
112            1.0 - 0.5 * ib
113        }
114    }
115}
116
117// ---------------------------------------------------------------------------
118// Normal
119// ---------------------------------------------------------------------------
120
121/// A normal (Gaussian) distribution with mean `mu` and standard deviation
122/// `sigma`.
123#[derive(Debug)]
124pub struct Normal {
125    mu: f64,
126    sigma: f64,
127}
128
129impl Normal {
130    /// Construct a normal distribution with mean `mu` and standard deviation
131    /// `sigma`.
132    ///
133    /// # Errors
134    ///
135    /// Returns an error string if `sigma <= 0`.
136    pub fn new(mu: f64, sigma: f64) -> Result<Self, &'static str> {
137        if sigma <= 0.0 {
138            return Err("standard deviation must be positive");
139        }
140        Ok(Normal { mu, sigma })
141    }
142
143    /// The mean `mu`.
144    pub fn mean(&self) -> f64 {
145        self.mu
146    }
147
148    /// The variance `sigma²`.
149    pub fn variance(&self) -> f64 {
150        self.sigma * self.sigma
151    }
152
153    /// Probability density at `x`.
154    pub fn pdf(&self, x: f64) -> f64 {
155        let z = (x - self.mu) / self.sigma;
156        (-0.5 * z * z).exp() / (self.sigma * (2.0 * std::f64::consts::PI).sqrt())
157    }
158}
159
160impl ContinuousCDF for Normal {
161    fn cdf(&self, x: f64) -> f64 {
162        // Φ(x) = erfc(-z)/2. Using 0.5 * (1 + erf(z)) would cancel to 0 in the
163        // left tail.
164        let z = (x - self.mu) / (self.sigma * std::f64::consts::SQRT_2);
165        0.5 * crate::special::erfc(-z)
166    }
167
168    fn sf(&self, x: f64) -> f64 {
169        let z = (x - self.mu) / (self.sigma * std::f64::consts::SQRT_2);
170        0.5 * crate::special::erfc(z)
171    }
172}
173
174#[cfg(test)]
175mod tests {
176    use super::*;
177
178    #[test]
179    fn normal_cdf_keeps_left_tail_precision() {
180        // Φ(-10) = 7.619853024160527e-24. Computing 0.5 * (1 + erf(z)) cancels
181        // to exactly 0 here, so the lower tail must come from erfc instead.
182        let n = Normal::new(0.0, 1.0).unwrap();
183        let want = 7.619_853_024_160_527e-24;
184        let got = n.cdf(-10.0);
185        assert!(((got - want) / want).abs() < 1e-8, "cdf(-10) = {got}");
186    }
187
188    #[test]
189    fn chi_squared_survival_matches_erfc_df1() {
190        // df = 1: sf(x) = erfc(sqrt(x/2)).
191        let chi = ChiSquared::new(1.0).unwrap();
192        let p = chi.sf(2.0);
193        assert!((p - crate::special::erfc(1.0)).abs() < 1e-14);
194    }
195
196    #[test]
197    fn chi_squared_df2_is_exponential() {
198        // df = 2: sf(x) = exp(-x/2).
199        let chi = ChiSquared::new(2.0).unwrap();
200        assert!((chi.sf(10.0) - (-5.0f64).exp()).abs() < 1e-14);
201    }
202
203    #[test]
204    fn students_t_cdf_boundaries() {
205        let t = StudentsT::new(0.0, 1.0, 4.0).unwrap();
206        // Symmetric about zero.
207        assert!((t.cdf(1.0) - t.sf(-1.0)).abs() < 1e-14);
208        assert!((t.cdf(0.0) - 0.5).abs() < 1e-14);
209        // cdf + sf = 1.
210        assert!((t.cdf(3.0) + t.sf(3.0) - 1.0).abs() < 1e-14);
211    }
212
213    #[test]
214    fn students_t_closed_form_df1() {
215        // df = 1 (Cauchy): two-sided p = 1 - 2/π * atan(|t|).
216        let t = StudentsT::new(0.0, 1.0, 1.0).unwrap();
217        let p = 2.0 * t.sf(2.0);
218        let exact = 1.0 - 2.0 * 2.0f64.atan() / std::f64::consts::PI;
219        assert!((p - exact).abs() < 1e-12, "p={p}, exact={exact}");
220    }
221
222    #[test]
223    fn students_t_critical_value_df4() {
224        // For df = 4 the two-sided 5% critical value is t = 2.776445.
225        let t = StudentsT::new(0.0, 1.0, 4.0).unwrap();
226        let p = 2.0 * t.sf(2.776445);
227        assert!((p - 0.05).abs() < 1e-6, "two-sided p={p}, expected 0.05");
228    }
229
230    #[test]
231    fn normal_basics() {
232        let n = Normal::new(0.0, 1.0).unwrap();
233        assert!((n.cdf(0.0) - 0.5).abs() < 1e-15);
234        assert!((n.pdf(0.0) - 1.0 / (2.0 * std::f64::consts::PI).sqrt()).abs() < 1e-15);
235        assert!((n.mean() - 0.0).abs() < 1e-15);
236        assert!((n.variance() - 1.0).abs() < 1e-15);
237    }
238
239    #[test]
240    fn invalid_parameters_rejected() {
241        assert!(ChiSquared::new(0.0).is_err());
242        assert!(ChiSquared::new(-1.0).is_err());
243        assert!(StudentsT::new(0.0, 1.0, 0.0).is_err());
244        assert!(StudentsT::new(0.0, 0.0, 1.0).is_err());
245        assert!(Normal::new(0.0, 0.0).is_err());
246    }
247}