I'm writing a C function to generate bandpass FIR filter coefficients using a simple window method (more details here FIR filters by windowing)

The important code snippet is the following (f1 and f2 are the low and high bandpass frequency, fs is the sampling frequency, all in hz, M is the taps number, the M coeffs are in h[0..M-1])

double* band_pass (double f1, double f2, double fs, int M) {
    double* h = (double*)calloc(M,sizeof(double));
    double w1 = 2.0*PI*f1/fs;
    double w2 = 2.0*PI*f2/fs;
    int MHALF = (M-1)/2;
    for (int n=0; n<MH; n++) {
        h[n] = (sin((n-MHALF)*w2) - sin((n-MHALF )*w1) ) / ((n-MHALF )*PI);
            h[n] = h[n] * (0.54-0.46*cos(2*PI*n/(M-1)));
        }
        h[M-n-1] = h[n];
    }
    h[MHALF ] = (w2 - w1) / PI;
    return h;
}

The coefficients (and so the filter) seem to work fine, but the gain in the bandpass isn't always unitary. I suppose I have to scale all the coefficients to obtain a unitary gain (in the bandpass).

So the question is: how do I scale the coefficients ?

Googling a bit I've found this formula for calc the BP filter gain:

gain += 2*h[n]*cos((n-MHALF)*(w1+w2)/2.);

then I have to divide all the coeffs for this gain. If it's correct, where does the formula come from and which are the formulas for the gain of the others kind of window fir filters LP, HP, bandstop ?

Thanks in advance.

  • The above code will work only for ODD Values of M wat about Even M value???????? PLZ HELP!! – user5374 Sep 4 '13 at 12:29
  • @Vignesh: Ask another question, then. :-) – Peter K. Sep 5 '13 at 12:17
  • How do you calculate the noise gain of an FIR? – Seth Oct 31 '13 at 20:59
up vote 13 down vote accepted

If you want the gain of your length-$N$ filter to be unity at a particular frequency, then you can calculate it directly:

$$ G = \sum_{k=0}^{N-1} h[k] e^{-j\omega k} $$

$G$ gives the gain of your filter at the frequency $\omega \in [0, 2\pi)$. If you would like to normalize the filter so that its gain at that frequency is $1$, then divide all of the filter coefficients by $G$. You would probably want to choose $\omega$ to lie in the middle of your passband.

You'll often see this for lowpass filters where you would like to have unity gain at DC. In that case, the formula simplifies to:

$$ G = \sum_{k=0}^{N-1} h[k] $$

i.e. $G$ is just the sum of the filter coefficients.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.