Skip to main content

xsf/scipy_special/
diric.rs

1//! Translated from <https://github.com/scipy/scipy/blob/38ecfef/scipy/special/_basic.py#L93-L192>
2
3use crate::xsf::cephes::dd_real::two_prod;
4
5/// Dirichlet kernel, also known as the periodic sinc function.
6///
7/// It is defined as
8///
9/// $D_n(x) = \sin(n x/2) / (n \sin(x/2))$
10///
11/// for $n > 0$.
12///
13/// Corresponds to [`scipy.special.diric`][diric] in SciPy.
14///
15/// [diric]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.diric.html
16///
17/// **Note:** The argument order in this crate is `(n, x)`, whereas SciPy uses `(x, n)`.
18///
19/// # Panics
20/// - Panics if `n` is zero.
21#[must_use]
22#[inline]
23pub fn diric(n: u32, x: f64) -> f64 {
24    assert!(n != 0, "diric: n must be a positive integer, got n = 0");
25
26    let x_half = x / 2.0;
27    if x_half == 0.0 {
28        return 1.0;
29    }
30
31    // Unlike in SciPy, sin(n x / 2) is evaluated at the exact product n (x / 2) = hi + lo, instead
32    // of fixing the result at +1 or -1 where |sin(x / 2)| < 1e-7.
33    //
34    // - Near x = 2 pi k the rounding error of n (x / 2) is large relative to sin(n x / 2), e.g. 3e-10
35    //   for diric(3, 2 pi + 1e-6), which the cutoff only hides for x even closer to 2 pi k.
36    // - The cutoff is wrong for large n, e.g. it gives 1 for diric(2^30, 1e-7) ~ -0.005.
37    let n_f64 = f64::from(n);
38    let (hi, lo) = two_prod(n_f64, x_half);
39    let ((sin_hi, cos_hi), (sin_lo, cos_lo)) = (hi.sin_cos(), lo.sin_cos());
40    (sin_hi * cos_lo + cos_hi * sin_lo) / (n_f64 * x_half.sin())
41}