one-indexed-vec 0.2.0

A one-based (1-indexed) wrapper around Vec<T>: element at position N is accessed via vec[N].
Documentation
//! Series expansion: Fourier and Taylor.

use crate::Vec1;

impl Vec1<f64> {
    /// Evaluates the Fourier series at `x`:
    /// `f(x) = a0/2 + Σ (a_n cos(n x) + b_n sin(n x))`.
    ///
    /// `self` provides cosine coefficients `a_n`, `b` provides sine
    /// coefficients `b_n`.
    ///
    /// ```rust
    /// use one_indexed_vec::{vec1, Vec1};
    /// use core::f64::consts::PI;
    ///
    /// // Square wave: only odd sine terms
    /// let a: Vec1<f64> = vec1![];
    /// let b = vec1![4.0/PI, 0.0, 4.0/(3.0*PI)];
    /// let v = a.fourier_eval(PI/2.0, 0.0, &b);
    /// assert!((v - 1.0).abs() < 0.2);
    /// ```
    pub fn fourier_eval(&self, x: f64, a0: f64, b: &Vec1<f64>) -> f64 {
        let mut result = a0 / 2.0;
        let max_len = self.len().max(b.len());
        for n in 1..=max_len {
            let nx = n as f64 * x;
            let an = if n <= self.len() { self[n] } else { 0.0 };
            let bn = if n <= b.len() { b[n] } else { 0.0 };
            result += an * libm::cos(nx) + bn * libm::sin(nx);
        }
        result
    }
}

/// Numerically computes Fourier coefficients of `f` over `[x_min, x_max]`.
///
/// Returns `(a0, a, b)`. Free function because it takes a callback, not a
/// `Vec1`.
pub fn fourier_coefficients<F>(
    f: F,
    n_terms: usize,
    n_samples: usize,
    x_min: f64,
    x_max: f64,
) -> (f64, Vec1<f64>, Vec1<f64>)
where
    F: Fn(f64) -> f64,
{
    assert!(n_samples > 0, "fourier_coefficients: n_samples must be > 0");
    let step = (x_max - x_min) / n_samples as f64;
    let mut a = zero_vec(n_terms);
    let mut b = zero_vec(n_terms);
    let mut sum_a0 = 0.0;

    for k in 0..n_samples {
        let x = x_min + k as f64 * step;
        let fx = f(x);
        sum_a0 += fx;
        for n in 1..=n_terms {
            let nx = n as f64 * x;
            a[n] += fx * libm::cos(nx);
            b[n] += fx * libm::sin(nx);
        }
    }

    let a0 = sum_a0 * 2.0 / n_samples as f64;
    let norm = 2.0 / n_samples as f64;
    for n in 1..=n_terms {
        a[n] *= norm;
        b[n] *= norm;
    }
    (a0, a, b)
}

/// Taylor series evaluation: `f(x) = Σ_{n=0}^{N} f^(n)(a)/n! * (x-a)^n`.
///
/// `derivs[n]` is the n-th derivative of `f` at `a`.
///
/// ```rust
/// use one_indexed_vec::math::series::taylor_eval;
///
/// // exp(x) at a=0: all derivatives equal 1
/// let derivs = [1.0; 10];
/// let v = taylor_eval(1.0, 0.0, &derivs);
/// assert!((v - core::f64::consts::E).abs() < 1e-4);
/// ```
pub fn taylor_eval(x: f64, a: f64, derivs: &[f64]) -> f64 {
    let mut result = 0.0;
    let mut fact = 1.0;
    let dx = x - a;
    for (n, d) in derivs.iter().enumerate() {
        if n > 0 {
            fact *= n as f64;
        }
        result += d * libm::pow(dx, n as f64) / fact;
    }
    result
}

fn zero_vec(n: usize) -> Vec1<f64> {
    let mut v = Vec1::with_capacity(n);
    for _ in 0..n {
        v.push(0.0);
    }
    v
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::vec1;
    use core::f64::consts::PI;

    #[test]
    fn fourier_square_wave() {
        let a: Vec1<f64> = vec1![];
        let b = vec1![4.0 / PI, 0.0, 4.0 / (3.0 * PI)];
        let v = a.fourier_eval(PI / 2.0, 0.0, &b);
        assert!((v - 1.0).abs() < 0.2);
    }

    #[test]
    fn fourier_constant() {
        let a: Vec1<f64> = vec1![];
        let b: Vec1<f64> = vec1![];
        let v = a.fourier_eval(0.5, 2.0, &b);
        assert!((v - 1.0).abs() < 1e-10);
    }

    #[test]
    fn fourier_coefficients_of_constant() {
        let (a0, a, b) = fourier_coefficients(|_| 1.0, 3, 1000, -PI, PI);
        assert!((a0 - 2.0).abs() < 0.01);
        for n in 1..=3 {
            assert!(a[n].abs() < 0.01);
            assert!(b[n].abs() < 0.01);
        }
    }

    #[test]
    fn taylor_exp() {
        let derivs = [1.0; 10];
        let v = taylor_eval(1.0, 0.0, &derivs);
        assert!((v - core::f64::consts::E).abs() < 1e-4);
    }

    #[test]
    fn taylor_sin() {
        let derivs = [0.0, 1.0, 0.0, -1.0, 0.0, 1.0, 0.0, -1.0];
        let v = taylor_eval(PI / 4.0, 0.0, &derivs);
        assert!((v - (PI / 4.0).sin()).abs() < 1e-6);
    }
}