Skip to main content

fixed_dsp/basic/
sin.rs

1use crate::common::tables::{SIN_TABLE_U16, SIN_TABLE_U32};
2
3const Q15_SHIFT: i32 = 16 - 10;
4const Q31_SHIFT: i32 = 32 - 10;
5
6/// x is in Q15 format (1.15 fixed-point), representing angles in the range [0, 2π].
7pub fn sin_i16(x: i16) -> i16 {
8    let mut x_bits = x as u16;
9    if x < 0 {
10        x_bits = x_bits.wrapping_add(0x8000);
11    }
12
13    let x_mapped = x_bits as i32;
14    let index = ((x_bits as u32) >> Q15_SHIFT) as usize;
15    let fract = (x_mapped - ((index as i32) << Q15_SHIFT)) << 9;
16
17    let a = SIN_TABLE_U16[index] as i16 as i32;
18    let b = SIN_TABLE_U16[index + 1] as i16 as i32;
19
20    let mut sin_val = ((0x8000_i32 - fract) * a) >> 16;
21    sin_val = ((sin_val << 16) + (fract * b)) >> 16;
22
23    (sin_val << 1) as i16
24}
25
26/// x is in Q31 format (1.31 fixed-point), representing angles in the range [0, 2π].
27pub fn sin_i32(x: i32) -> i32 {
28    let mut x_bits = x as u32;
29    if x < 0 {
30        x_bits = x_bits.wrapping_add(0x8000_0000);
31    }
32
33    let x_mapped = x_bits as i64;
34    let index = (x_bits >> Q31_SHIFT) as usize;
35    let fract = (x_mapped - ((index as i64) << Q31_SHIFT)) << 9;
36
37    let a = SIN_TABLE_U32[index] as i32 as i64;
38    let b = SIN_TABLE_U32[index + 1] as i32 as i64;
39
40    let mut sin_val = ((0x8000_0000_i64 - fract) * a) >> 32;
41    sin_val = ((sin_val << 32) + (fract * b)) >> 32;
42
43    (sin_val << 1) as i32
44}