dsp.js icon indicating copy to clipboard operation
dsp.js copied to clipboard

Invalid RFFT spectrum 0th bin

Open BloodyAltair opened this issue 4 years ago • 1 comments

Hi I think I found a bug in spectrum calculating part of RFFT algorithm Lets assume that we have fft_size = 2048 So, we need to fill spectrum from 0 to 1023 with values of 2 / 2048 * sqrt(real_vals[0-1023] * real_vals[0-1023] + imaginary_vals[1024-2047] * imaginary_vals[1024-2047]), right?

Now see lines 812 and 825 of this algorithm

On line 812 cycle iterator i will take values from 1023 to 1. For this reason real_vals[0] and imaginary_vals[2047] will not be affected by the loop.

So we will need to fill 0th spectrum entry after cycle. It happens on line 825 the following way spectrum[0] = bSi * x[0]; (as for now)

I think that it should be done something like this: spectrum[0] = bSi * sqrt(x[0] * x[0] + x[2047] * x[2047]);

I'm not so good at FFTs and algorithms yet, thats why i've opened an issue instead of PR

BloodyAltair avatar May 19 '21 03:05 BloodyAltair

Not commenting on what happens in these particular lines, but spectrum[0] should be the arithmetic mean of your input signal. Often, you'll also get overall better numerical precision by subtracting that mean before passing your signal to the FFT (and set spectrum[0] manually afterwards).

harbulot avatar Oct 23 '21 14:10 harbulot