lib_jsl_dsp/discrete/sinc.rs
1//! This module provides implementations of the sinc function and its normalized version, as well as functions to generate centered sinc windows. The sinc function is defined as sin(pi * x) / (pi * x) for x != 0 and is equal to 1 at x = 0. The normalized sinc function is defined similarly but with a factor of 2 in the argument. The centered sinc window functions generate a vector of sinc values that are centered around zero, which can be used in various signal processing applications, such as interpolation and filter design.
2//!
3//! See the book entry [FIR design: windows, frequency sampling and Parks-McClellan](https://jwkunz.github.io/lib_jsl/book/filters/fir-design.html#the-window-method).
4
5use std::f64::consts::PI;
6pub fn sinc(x: f64) -> f64 {
7 if x.abs() < 1e-15 {
8 1.0
9 } else {
10 (PI * x).sin() / (PI * x)
11 }
12}
13
14pub fn sinc_normalized(x: f64) -> f64 {
15 if x.abs() < 1e-15 {
16 1.0
17 } else {
18 (2.0 * PI * x).sin() / (2.0 * PI * x)
19 }
20}
21
22/// `n` samples of `sinc(cut_off · t)` (or of the normalised sinc for
23/// [`generate_centered_sinc_normalized`]) at points `t` spaced `1/n` apart and centred on zero,
24/// so `t` spans about `[−1/2, 1/2]`. The result is a smooth taper whose width depends on `cut_off`
25/// (for `cut_off ≤ 2` every value is positive), used as a smoothing kernel; it is not the impulse
26/// response of a low-pass filter with that cutoff, for which see `firwin`.
27pub fn generate_centered_sinc(n : usize, cut_off: f64) -> Vec<f64> {
28 let m = n as f64;
29 let mut sinc_vec = Vec::with_capacity(n);
30 for i in 0..n {
31 let x = (i as f64 - (m - 1.0) / 2.0) / m;
32 sinc_vec.push(sinc(x * cut_off));
33 }
34 sinc_vec
35}
36
37pub fn generate_centered_sinc_normalized(n : usize, cut_off: f64) -> Vec<f64> {
38 let m = n as f64;
39 let mut sinc_vec = Vec::with_capacity(n);
40 for i in 0..n {
41 let x = (i as f64 - (m - 1.0) / 2.0) / m;
42 sinc_vec.push(sinc_normalized(x * cut_off ));
43 }
44 sinc_vec
45}