use crate::Vec1;
impl Vec1<f64> {
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
}
}
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)
}
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);
}
}