FFT filter vs lfilter in python
Question: I have some troubles when applying bandpass filter to signal in Python. Have
tried the following to things:

  * Do the box window "by hand", i.e. do the FFT on the signal, apply the filter with a box window and the do the IFFT to get back to the time domain.
  * Use the scipy.signal module where I use firwin2 to construct the filter and then lfilter to to the filtering.

Futhermore I have done the same filtering in the audio program Cool Edit and
compared the result from the above two tests.

As can be seen (I am a new user so I can not post my png fig), the results
from the FFT and scipy.signal are very different. When compare to the result
from Cool edit, the FFT is close, however not identical. Code as below:

    
    
    # imports 
    from pylab import *
    import os
    import scipy.signal as signal
    
    # load data 
    tr=loadtxt('tr6516.txt',skiprows=1)
    
    sr = 500            # [samples/s]
    nf = sr/2.0         # Nyquist frequence
    W = 512            # Window widht for filtering
    N=float(8192)       # Fourier settings
    Ns = len(tr[:,0])   # Total number of samples
    
    # Create inpulse responce from the filter
    fv=12.25
    w    =0.5
    r    =0.5*w
    Hz=[0, fv-w-r, fv-w, fv+w, fv+w+r, nf]
    ff=[0, 0,      1,    1,    0,      0]
    b = signal.firwin2(W,Hz,ff,nfreqs=N+1,nyq=nf)
    SigFilter = signal.lfilter(b, 1, tr[:,1])
    
    # Fourier transform
    X1 = fft(tr[:,1],n=int(N))
    X1 = fftshift(X1)
    F1 = arange(-N/2.0,N/2.0)/N*sr
    
    # Filter data
    ff=[0,1,1,0]
    fv=12.25
    w    =0.5
    r    =0.5*w
    Hz=[fv-w-r,fv-w,fv+w,fv+w+r]
    k1=interp(-F1,Hz,ff)+interp(F1,Hz,ff)
    X1_f=X1*k1
    X1_f=ifftshift(X1_f)
    x1_f=ifft(X1_f,n=int(N))
    

Can anyone explain to me why this difference? The filtering in Cool edit has
been done using the same settings as in scipy.signal (hanning window, window
width 512). Or have I got this all totaly wrong.

Best regards, Anders

Above code:

![enter image description here](http://i.stack.imgur.com/afeDZ.png)

Compared with Cool Edit:

![enter image description here](http://i.stack.imgur.com/943hz.png)

![enter image description here](http://i.stack.imgur.com/sWdYd.png)


Answer: Small differences can be explained by the libraries using different algorithms
that accumulate error slightly differently.

For example, if you compute the DFT using a radix-2 FFT, a split-radix FFT and
an ordinary DFT, the results will all be slightly different. In fact the
ordinary DFT has worse accuracy than all decent implementations of an FFT
because it uses many more floating point operations, and thus it accumulates
more error.

Could this explain the close (but not identical) results you are seeing?

