Ηello! I hope this is an acceptable sort of question.
Going through some code used for signal processing I came upon an odd function:
let kInd = (k1, pow) => {
let k2 = 0;
let k3 = 0;
for (let i = 0; i < pow; i++) {
k3 = k1 >> 1;
k2 = 2 * (k2 - k3) + k1;
k1 = k3;
}
return k2;
};
This function is called towards the end of a fourier transform calculation to swap indexes in the real+imaginary pair of arrays:
let fft = samples => {
let pow = Math.log2(samples.length); // `samples.length` is expected to be 2^int
// ... a bunch of code to generate `rBuff` and `iBuff` arrays representing
// real and imaginary components of fourier values
// Now make use of `kInd`; conditionally swap some indexes in `rBuff` and `iBuff`:
for (let i = 0; i < rBuff.length; i++) {
let k = kInd(i, pow);
if (k >= i) continue;
[ rBuff[i], rBuff[k] ] = [ rBuff[k], rBuff[i] ];
[ iBuff[i], iBuff[k] ] = [ iBuff[k], iBuff[i] ];
}
// ... A bit of code to convert to power spectrum and return result
};
My question is: what the heck is kInd
doing? I've run it to output some example values; it looks like it outputs sums of powers of 2 in a nearly random order as its k1
parameter increments. Small changes to kInd
lead to completely wrong results from fft
.
Thanks!
(Note: let me know if more code would help. Trying to keep this as brief as possible for the reader's sake!)
This implements the butterfly operation of the FFT algorithm.
For example, running...
console.log([0,1,2,3,4,5,6,7].map(i => kInd(i, 3)))
...prints...
[ 0, 4, 2, 6, 1, 5, 3, 7 ]
... which is the mapping in the diagram here:
http://www.alwayslearn.com/DFT%20and%20FFT%20Tutorial/DFTandFFT_FFT_Butterfly_8_Input.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With