AllenDowney / ThinkDSP

Think DSP: Digital Signal Processing in Python, by Allen B. Downey.
https://allendowney.github.io/ThinkDSP/
3.97k stars 3.23k forks source link

Spectrum convolve issue - even number of samples #74

Closed hchesser closed 2 years ago

hchesser commented 4 years ago

When I use an even number of frequency samples to convole 2 spectra, this seem to generate a frequency bin error. If I use an odd number of samples there is no error

Use case: AM modulated signal (like Chp 11 of ThinkDSP) - modulating signal is a 100 Hz SquareSignal (square wave) use low_pass to limit bandwidth to 1000 Hz (so you have spikes at 100, 300, 500...900 Hz). The carrier frequency is a CosSignal, frequency of 10000 Hz. I use a framerate of 100000 to sample both waves for 1 second and convert to (full) spectra, then convolve them together. I get sidebands as expected but at 10101, 10301, ... 10901 and not quite mirror imaged 9901, 9701...90101 Hz and then mirror imaged on the negative frequency side - so a frequency bin error of 1.

Fix seems to be to use an odd number of samples (or roll the convolved hs array by -1) - I used a framerate of 100001 for example. Not sure if this is a known issue with numpy fft.fftshift or not or should we expect this from theory? Anyway maybe warn the user in thinkdsp or perhaps pad the input spectra or the convolved spectrum somehow?

AllenDowney commented 3 years ago

I will investigate this. Do you have a minimal test case that causes the error?

Thanks!