Skip to main content

lib_jsl_integration/
gaussian_quadrature.rs

1//! Gaussian quadrature rules: Gauss-Legendre, Gauss-Hermite and generalized Gauss-Laguerre.
2//!
3//! An n-point Gauss rule integrates `w(x) p(x)` exactly for every polynomial `p` of degree up to
4//! `2n − 1`. Nodes are the zeros of the orthogonal polynomial of degree n, found by Newton's
5//! method on the three-term recurrence from asymptotic starting guesses (as in Numerical
6//! Recipes), so rules with hundreds of points are cheap and accurate to rounding.
7
8use crate::can_integrate::CanIntegrate1D;
9use lib_jsl_core::ErrorsJSL;
10use lib_jsl_special_functions::ln_gamma;
11use std::f64::consts::PI;
12
13/// Nodes and weights of a quadrature rule.
14#[derive(Debug, Clone)]
15pub struct QuadratureRule {
16    pub nodes: Vec<f64>,
17    pub weights: Vec<f64>,
18}
19
20impl QuadratureRule {
21    /// `Σ w_i f(x_i)`.
22    pub fn apply<F: Fn(f64) -> f64>(&self, f: F) -> f64 {
23        self.nodes.iter().zip(&self.weights).map(|(&x, &w)| w * f(x)).sum()
24    }
25}
26
27fn check(n: usize) -> Result<(), ErrorsJSL> {
28    if n == 0 {
29        return Err(ErrorsJSL::InvalidInputRange("A quadrature rule needs at least one point."));
30    }
31    Ok(())
32}
33
34/// The n-point Gauss-Legendre rule for `∫_{−1}^{1} f(x) dx`, nodes ascending.
35///
36/// The nodes are the zeros of the Legendre polynomial `P_n` and the weights are
37/// `w_i = 2 / ((1 − x_i²) P_n'(x_i)²)`. The rule is exact for polynomials of degree `2n − 1`.
38/// Map it to `[a, b]` with `x = (a + b)/2 + (b − a)/2 · t`, or use [`GaussLegendreEngine`].
39///
40/// ```
41/// use lib_jsl_integration::gaussian_quadrature::gauss_legendre;
42///
43/// let rule = gauss_legendre(3).unwrap();
44/// // Three points integrate x⁴ exactly (degree 4 ≤ 2·3 − 1): ∫ x⁴ dx over [−1, 1] = 2/5.
45/// assert!((rule.apply(|x| x.powi(4)) - 0.4).abs() < 1e-15);
46/// // The weights sum to the length of the interval.
47/// assert!((rule.weights.iter().sum::<f64>() - 2.0).abs() < 1e-15);
48/// ```
49pub fn gauss_legendre(n: usize) -> Result<QuadratureRule, ErrorsJSL> {
50    check(n)?;
51    let mut nodes = vec![0.0; n];
52    let mut weights = vec![0.0; n];
53    // ANCHOR: legendre_newton
54    // Nodes come in ± pairs, so only the non-negative half is computed.
55    for i in 0..n.div_ceil(2) {
56        // Asymptotic first guess for the i-th zero (Tricomi).
57        let mut z = (PI * (i as f64 + 0.75) / (n as f64 + 0.5)).cos();
58        let mut derivative = 1.0;
59        for _ in 0..100 {
60            // Bonnet's recurrence: j P_j = (2j − 1) x P_{j−1} − (j − 1) P_{j−2}.
61            let (mut p1, mut p2) = (1.0, 0.0);
62            for j in 1..=n {
63                let p3 = p2;
64                p2 = p1;
65                p1 = ((2 * j - 1) as f64 * z * p2 - (j - 1) as f64 * p3) / j as f64;
66            }
67            // P_n'(x) = n (x P_n − P_{n−1}) / (x² − 1), then a Newton step.
68            derivative = n as f64 * (z * p1 - p2) / (z * z - 1.0);
69            let dz = p1 / derivative;
70            z -= dz;
71            if dz.abs() <= 1e-16 {
72                break;
73            }
74        }
75        nodes[i] = -z;
76        nodes[n - 1 - i] = z;
77        let w = 2.0 / ((1.0 - z * z) * derivative * derivative);
78        weights[i] = w;
79        weights[n - 1 - i] = w;
80    }
81    // ANCHOR_END: legendre_newton
82    if n % 2 == 1 {
83        nodes[n / 2] = 0.0;
84    }
85    Ok(QuadratureRule { nodes, weights })
86}
87
88/// The n-point Gauss-Hermite rule for `∫_{−∞}^{∞} e^{−x²} f(x) dx` (physicists' weight), nodes
89/// ascending. For the probabilists' weight `e^{−x²/2}` scale nodes by √2 and weights by √2.
90pub fn gauss_hermite(n: usize) -> Result<QuadratureRule, ErrorsJSL> {
91    check(n)?;
92    let pim4 = PI.powf(-0.25);
93    let mut z_values = vec![0.0; n];
94    let mut w_values = vec![0.0; n];
95    let nf = n as f64;
96    let mut z = 0.0;
97    for i in 0..n.div_ceil(2) {
98        z = match i {
99            0 => (2.0 * nf + 1.0).sqrt() - 1.85575 * (2.0 * nf + 1.0).powf(-1.0 / 6.0),
100            1 => z - 1.14 * nf.powf(0.426) / z,
101            2 => 1.86 * z - 0.86 * z_values[0],
102            3 => 1.91 * z - 0.91 * z_values[1],
103            _ => 2.0 * z - z_values[i - 2],
104        };
105        let mut derivative = 1.0;
106        for _ in 0..100 {
107            // Orthonormal Hermite recurrence (stable for large n).
108            let (mut p1, mut p2) = (pim4, 0.0);
109            for j in 0..n {
110                let p3 = p2;
111                p2 = p1;
112                let jf = j as f64;
113                p1 = z * (2.0 / (jf + 1.0)).sqrt() * p2 - (jf / (jf + 1.0)).sqrt() * p3;
114            }
115            derivative = (2.0 * nf).sqrt() * p2;
116            let dz = p1 / derivative;
117            z -= dz;
118            if dz.abs() <= 1e-15 * z.abs().max(1.0) {
119                break;
120            }
121        }
122        z_values[i] = z;
123        w_values[i] = 2.0 / (derivative * derivative);
124    }
125    // Store ascending: the computed zeros are the positive ones, largest first.
126    let mut nodes = vec![0.0; n];
127    let mut weights = vec![0.0; n];
128    for i in 0..n.div_ceil(2) {
129        nodes[n - 1 - i] = z_values[i];
130        nodes[i] = -z_values[i];
131        weights[i] = w_values[i];
132        weights[n - 1 - i] = w_values[i];
133    }
134    if n % 2 == 1 {
135        nodes[n / 2] = 0.0;
136    }
137    Ok(QuadratureRule { nodes, weights })
138}
139
140/// The n-point generalized Gauss-Laguerre rule for `∫_0^∞ x^α e^{−x} f(x) dx` (`α > −1`), nodes
141/// ascending.
142pub fn gauss_laguerre(n: usize, alpha: f64) -> Result<QuadratureRule, ErrorsJSL> {
143    check(n)?;
144    if alpha.is_nan() || alpha <= -1.0 {
145        return Err(ErrorsJSL::InvalidInputRange("The Laguerre exponent must exceed -1."));
146    }
147    let nf = n as f64;
148    let mut nodes = vec![0.0; n];
149    let mut weights = vec![0.0; n];
150    let mut z = 0.0;
151    let log_norm = ln_gamma(alpha + nf) - ln_gamma(nf);
152    for i in 0..n {
153        z = match i {
154            0 => (1.0 + alpha) * (3.0 + 0.92 * alpha) / (1.0 + 2.4 * nf + 1.8 * alpha),
155            1 => z + (15.0 + 6.25 * alpha) / (1.0 + 0.9 * alpha + 2.5 * nf),
156            _ => {
157                let ai = (i - 1) as f64;
158                z + ((1.0 + 2.55 * ai) / (1.9 * ai) + 1.26 * ai * alpha / (1.0 + 3.5 * ai)) * (z - nodes[i - 2]) / (1.0 + 0.3 * alpha)
159            }
160        };
161        let (mut derivative, mut previous) = (1.0, 0.0);
162        for _ in 0..100 {
163            let (mut p1, mut p2) = (1.0, 0.0);
164            for j in 1..=n {
165                let p3 = p2;
166                p2 = p1;
167                let jf = j as f64;
168                p1 = ((2.0 * jf - 1.0 + alpha - z) * p2 - (jf - 1.0 + alpha) * p3) / jf;
169            }
170            derivative = (nf * p1 - (nf + alpha) * p2) / z;
171            previous = p2;
172            let dz = p1 / derivative;
173            z -= dz;
174            if dz.abs() <= 1e-15 * z.abs().max(1e-300) {
175                break;
176            }
177        }
178        nodes[i] = z;
179        weights[i] = -log_norm.exp() / (derivative * nf * previous);
180    }
181    Ok(QuadratureRule { nodes, weights })
182}
183
184/// Integrates `f` over `[a, b]` with a fixed n-point Gauss-Legendre rule.
185#[derive(Debug, Clone)]
186pub struct GaussLegendreEngine {
187    rule: QuadratureRule,
188    lower_bound: f64,
189    upper_bound: f64,
190}
191
192impl GaussLegendreEngine {
193    pub fn new(number_of_points: usize, lower_bound: f64, upper_bound: f64) -> Result<Self, ErrorsJSL> {
194        Ok(GaussLegendreEngine { rule: gauss_legendre(number_of_points)?, lower_bound, upper_bound })
195    }
196}
197
198impl CanIntegrate1D for GaussLegendreEngine {
199    fn set_lower_bound(&mut self, x: f64) {
200        self.lower_bound = x;
201    }
202    fn set_upper_bound(&mut self, x: f64) {
203        self.upper_bound = x;
204    }
205    fn integrate<F>(&self, f: F) -> Result<f64, ErrorsJSL>
206    where
207        F: Fn(f64) -> f64,
208    {
209        let half = 0.5 * (self.upper_bound - self.lower_bound);
210        let mid = 0.5 * (self.upper_bound + self.lower_bound);
211        Ok(half * self.rule.apply(|t| f(mid + half * t)))
212    }
213}
214
215#[cfg(test)]
216mod tests {
217    use super::*;
218    use lib_jsl_special_functions::gamma;
219
220    fn close(a: f64, b: f64, tol: f64) -> bool {
221        (a - b).abs() <= tol * (1.0 + b.abs())
222    }
223
224    #[test]
225    fn legendre_rules_are_exact_to_degree_2n_minus_1() {
226        for n in [1, 2, 3, 5, 10, 64, 200] {
227            let rule = gauss_legendre(n).unwrap();
228            assert!(close(rule.weights.iter().sum(), 2.0, 1e-14), "n={n}");
229            assert!(rule.nodes.windows(2).all(|w| w[0] < w[1]));
230            for k in 0..(2 * n).min(30) {
231                let exact = if k % 2 == 1 { 0.0 } else { 2.0 / (k + 1) as f64 };
232                assert!(close(rule.apply(|x| x.powi(k as i32)), exact, 1e-13), "n={n} k={k}");
233            }
234        }
235        // One degree higher is no longer exact.
236        let r3 = gauss_legendre(3).unwrap();
237        assert!((r3.apply(|x| x.powi(6)) - 2.0 / 7.0).abs() > 1e-3);
238        let engine = GaussLegendreEngine::new(20, 0.0, PI).unwrap();
239        assert!(close(engine.integrate(f64::sin).unwrap(), 2.0, 1e-15));
240        assert!(gauss_legendre(0).is_err());
241    }
242
243    #[test]
244    fn hermite_rules_integrate_gaussian_moments() {
245        for n in [1, 2, 5, 20, 100] {
246            let rule = gauss_hermite(n).unwrap();
247            assert!(close(rule.weights.iter().sum(), PI.sqrt(), 1e-13), "n={n}");
248            assert!(rule.nodes.windows(2).all(|w| w[0] < w[1]));
249            // ∫ e^{−x²} x^{2k} = Γ(k + ½).
250            for k in 0..n.min(10) {
251                assert!(close(rule.apply(|x| x.powi(2 * k as i32)), gamma(k as f64 + 0.5), 1e-12), "n={n} k={k}");
252            }
253        }
254        let rule = gauss_hermite(30).unwrap();
255        assert!(close(rule.apply(f64::cos), PI.sqrt() * (-0.25f64).exp(), 1e-14));
256    }
257
258    #[test]
259    fn laguerre_rules_integrate_gamma_moments() {
260        for &alpha in &[0.0, -0.5, 1.5, 4.0] {
261            for n in [1, 3, 8, 40] {
262                let rule = gauss_laguerre(n, alpha).unwrap();
263                assert!(rule.nodes.windows(2).all(|w| w[0] < w[1]) && rule.nodes[0] > 0.0);
264                // ∫ x^α e^{−x} x^k = Γ(α + k + 1).
265                for k in 0..(2 * n).min(12) {
266                    let want = gamma(alpha + k as f64 + 1.0);
267                    assert!(close(rule.apply(|x| x.powi(k as i32)), want, 1e-11 * want.max(1.0)), "α={alpha} n={n} k={k}");
268                }
269            }
270        }
271        // ∫_0^∞ e^{−x} sin x dx = ½.
272        assert!(close(gauss_laguerre(40, 0.0).unwrap().apply(f64::sin), 0.5, 1e-12));
273        assert!(gauss_laguerre(4, -1.0).is_err());
274    }
275}