Η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!)