Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Spectra at chosen frequencies: Goertzel, chirp-z and Fourier integrals

ProblemEvaluate a transform at a few frequencies, or on a fine grid over a narrow band, or the continuous Fourier integral of a function, without computing a full FFT
Devised byGerald Goertzel (1958); Lawrence Rabiner, Ronald Schafer and Charles Rader (1969), the chirp-z transform, after Leo Bluestein (1968)
AccuracyThe chirp-z transform agrees with SciPy’s czt to ; Fourier integrals converge spectrally for smooth, decaying functions (table below)
CostGoertzel: real multiply-adds per bin. Chirp-z: three FFTs of length for output points
Read firstThe fast Fourier transform, Bluestein’s algorithm and the fractional Fourier transform
APIgoertzel, goertzel_power, goertzel_frequency, chirpz, fourier_integral (FourierDirection)

Overview

The FFT computes all DFT bins at once in operations. Often fewer are wanted. Tone detection, as in telephone keypads, needs a handful of known frequencies, and the Goertzel algorithm computes each with a second-order recursion of one multiply-add per sample. Zooming in on a narrow band at fine resolution needs many frequencies, but not the FFT’s evenly spaced bins around the whole circle; the chirp-z transform evaluates the -transform on any arc or spiral of equally spaced points, again with FFTs. The same machinery computes continuous Fourier integrals of sampled functions at chosen frequencies.

Where it is used

Not every spectrum needs a full FFT.

  • Tone detection. The Goertzel algorithm detects a few frequencies: DTMF touch-tone decoding in telephones, and detecting a particular carrier or a power-line harmonic.
  • Zoomed spectra. The chirp-z transform evaluates a narrow band on a fine grid, as in vibration analysis around a machine’s rotation frequency and in radar Doppler processing.
  • Fourier integrals. Computing the continuous transform of a function at chosen frequencies.

History

Gerald Goertzel (1958) described the recursion for evaluating single terms of a trigonometric series, and it became the standard detector for the dual-tone multi-frequency (DTMF) signals of touch-tone telephones. Leo Bluestein (1968) noticed that the identity turns a DFT of any length into a convolution with a “chirp”, and Lawrence Rabiner, Ronald Schafer and Charles Rader (1969) generalised it to the chirp-z transform. The FFT chapter uses the same identity for prime-length transforms.

The idea

Goertzel’s recursion

An FFT computes all frequency bins at once. When only one or two frequencies matter, as in detecting a telephone dialling tone, most of that work is wasted. Goertzel’s algorithm computes a single bin with a two-term recursion.

A DFT bin as a filter output. The bin is the sum with . Consider the one-pole recursive filter , starting from zero. Unrolling it, , which is the wanted sum multiplied by the known phase factor . So running this filter over the block and reading its final output gives the bin. The filter has a single pole at on the unit circle: it resonates at exactly the frequency of interest.

Making it real. That filter needs a complex multiplication per sample. Multiplying its transfer function above and below by the conjugate factor gives an equivalent filter whose recursive part has real coefficients, with the two poles :

This is run over the whole block with one real multiplication per sample. The complex arithmetic is postponed to a single step at the end, . If only the power is wanted, even that is unnecessary:

Nothing in the derivation requires to be an integer, so any frequency can be targeted, not only the bin centres of an FFT.

When it pays. Each bin costs one real multiply per sample; the FFT costs about per sample for all bins. In practice the FFT’s efficiency narrows the margin:

Table 15.5. Goertzel against a full FFT: time and break-even number of bins.

samplesone Goertzel bin (µs)real FFT, all bins (µs)bins before the FFT is cheaper
2560.70.71
40967.95.91
65536121.6163.41

Here one Goertzel bin costs half an FFT, so Goertzel pays off for one or two frequencies, or when samples arrive one at a time and the result is wanted the moment the block ends.

The chirp-z transform

The DFT evaluates the spectrum at frequencies spaced evenly round the whole unit circle. To look closely at a narrow band, one wants many points within that band only. The chirp-z transform evaluates at points , which start at and advance by the constant ratio . With the points lie on an arc of the unit circle, beginning at any frequency, with any spacing, and need not equal . (With other magnitudes they lie on a spiral.)

It is computed by the same device as Bluestein’s algorithm, of which it is the general form. Substituting gives a sum containing , and writing separates the exponent into parts depending on , on and on :

The sum is a convolution of the premultiplied input with the chirp , computed with FFTs in operations. Zooming on two tones 1.8 bins apart in a 256-sample record:

Figure 15.5. Chirp-z zoom.

The FFT’s bins fall on either side of the two peaks; 400 chirp-z points over the band trace the response between them. Zooming adds points, not resolution. The two peaks are resolved because they are more than one bin apart, and the chirp-z transform shows the shape the FFT samples coarsely. (Zero-padding the FFT would do the same, at the cost of transforming the whole circle.)

Fourier integrals

The continuous transform of a function on is approximated by the trapezoidal rule on equally spaced samples, and evaluated at equally spaced frequencies in any range by the chirp-z transform. For smooth functions that decay at the ends of the interval, the trapezoidal rule converges spectrally:

Table 15.6. Accuracy of a Fourier integral computed with the trapezoidal rule.

samples on [−8, 8] (and frequencies on [0, 4])largest error against √(2π) e^(−ω²/2)
164.2e-1
321.3e-14
644.9e-15
1283.4e-13

With 32 samples the Gaussian’s transform is exact to rounding. With 16, the sample spacing exceeds the Nyquist spacing for the frequencies requested, and the result aliases.

Algorithm

Goertzel, for one frequency and a block of samples.

  1. Precompute . Set .
  2. For each sample : . Only the two latest values of are kept.
  3. After the last sample, compute the complex bin , or the power .

Cost: one multiplication and two additions per sample.

Chirp-z transform, for samples and output points .

  1. Premultiply: for .
  2. Form the chirp for .
  3. Convolve the two with FFTs of a power-of-two length at least .
  4. Postmultiply: is the convolution output for lag times , .

Fourier integral of over at equally spaced frequencies.

  1. Sample at equally spaced points and multiply by the trapezoidal weights (the spacing, halved at the two ends).
  2. Evaluate the resulting sum at all the requested frequencies at once with the chirp-z transform, taking from the product of the sample spacing and the frequency spacing and from the first frequency.
  3. Multiply by the phase factor that accounts for the starting point of the interval.

Implementation

    let omega = TAU * k / n as f64;
    let coefficient = 2.0 * omega.cos();
    let (mut s1, mut s2) = (0.0, 0.0);
    for &v in x {
        let s0 = v + coefficient * s1 - s2;
        s2 = s1;
        s1 = s0;
    }
    // y_{N−1} = s_{N−1} − e^{−iω} s_{N−2} = e^{iω(N−1)} X(k); undo the phase.
    let y = Complex::new(s1, 0.0) - Complex::from_polar(1.0, -omega) * s2;
    Ok(y * Complex::from_polar(1.0, -omega * (n - 1) as f64))
    let g_len = m + n - 1;
    let conv_len = n + g_len - 1;
    let fft_len = conv_len.next_power_of_two();

    let mut y = vec![Complex::new(0.0, 0.0); fft_len];
    for idx in 0..n {
        let idxf = idx as f64;
        let a_term = complex_powf(a, -idxf)?;
        let w_term = complex_powf(w, 0.5 * idxf * idxf)?;
        y[idx] = data_in[idx].to_complex() * a_term * w_term;
    }

    let mut v = vec![Complex::new(0.0, 0.0); fft_len];
    for q in (-(n as isize) + 1)..=(m as isize - 1) {
        let qf = q as f64;
        v[(q + (n as isize - 1)) as usize] = complex_powf(w, -0.5 * qf * qf)?;
    }
  • chirpz defaults to , , , which reproduces the DFT.
  • fourier_integral takes a plain function fn(f64) -> Complex<f64>; FourierDirection::Inverse includes the factor .

In practice

//! Evaluating spectra at chosen frequencies: Goertzel, the chirp-z zoom and Fourier integrals.

use lib_jsl_dsp::continuous::spectral::fourier_integrals::{FourierDirection, fourier_integral};
use lib_jsl_dsp::discrete::spectral::chirpz::chirpz;
use lib_jsl_dsp::discrete::spectral::goertzel::{goertzel_frequency, goertzel_power};
use num_complex::Complex;
use std::f64::consts::PI;

fn main() {
    // DTMF digit 5: 770 Hz and 1336 Hz, 205 samples at 8 kHz.
    let fs = 8000.0;
    let x: Vec<f64> = (0..205).map(|n| (2.0 * PI * 770.0 * n as f64 / fs).sin() + (2.0 * PI * 1336.0 * n as f64 / fs).sin()).collect();
    for f in [697.0, 770.0, 852.0, 941.0, 1209.0, 1336.0, 1477.0] {
        print!("{f}: {:6.1}   ", goertzel_frequency(&x, f, fs).unwrap().norm());
    }
    println!();
    println!("power in bin 20: {:.1}", goertzel_power(&x, 20.0).unwrap());
    // Zoom on 700-850 Hz with 16 points.
    let w = Complex::from_polar(1.0, -2.0 * PI * 10.0 / fs);
    let a = Complex::from_polar(1.0, 2.0 * PI * 700.0 / fs);
    let z = chirpz(&x, Some(16), Some(w), Some(a)).unwrap();
    let peak = (0..16).max_by(|&i, &j| z[i].norm().total_cmp(&z[j].norm())).unwrap();
    println!("chirp-z peak at {} Hz", 700 + 10 * peak);
    // The Fourier transform of a unit box on [-1, 1] is 2 sin(ω)/ω.
    let r = fourier_integral(|_| Complex::new(1.0, 0.0), -1.0, 1.0, 0.0, 6.0, 61, FourierDirection::Forward).unwrap();
    for (w, v) in r.omega.iter().zip(r.values.iter()).step_by(20) {
        let exact = if *w == 0.0 { 2.0 } else { 2.0 * w.sin() / w };
        println!("F({w:.1}) = {:.4} (exact {exact:.4})", v.re);
    }
}
697:    7.6   770:  102.5   852:    5.6   941:    6.7   1209:    7.7   1336:  102.5   1477:    8.1   
power in bin 20: 8169.6
chirp-z peak at 770 Hz
F(0.0) = 2.0000 (exact 2.0000)
F(2.0) = 0.9090 (exact 0.9093)
F(4.0) = -0.3778 (exact -0.3784)
F(6.0) = -0.0928 (exact -0.0931)

The 205-sample block is the length used by DTMF decoders, which places the eight tones close to bin centres; the digit is “5” (770 Hz and 1336 Hz). The box function’s transform converges only at second order, because the box is discontinuous at the ends of its support.

Strengths

  • Goertzel: minimal cost and memory for a few frequencies, any frequency, and streaming operation.
  • Chirp-z: any band at any spacing with FFT efficiency; the DFT of any length.

Weaknesses

  • Neither improves resolution, which is fixed by the record length.
  • The Goertzel recursion’s error grows with for frequencies near 0 or Nyquist, where .

Exercises

  1. Derive the Goertzel recursion from the filter by multiplying numerator and denominator by .
  2. Show that the power formula equals .
  3. Prove Bluestein’s identity , and count the FFT lengths needed for an -point chirp-z transform of samples.
  4. Explain why the trapezoidal rule converges spectrally for a function whose derivatives vanish at both ends of the interval.
  5. Choose a block length for DTMF detection at 8 kHz so that all eight tones are within 0.2 bins of integer bins.
Hints and answers
  1. The recursion is : the denominator is real, and the numerator is applied once at the end.
  2. After steps up to a phase; take its squared modulus: .
  3. by expanding the square. The chirp-z transform needs one convolution of length at least , so three FFTs of that length (rounded up to a convenient size): two forward and one inverse.
  4. The Euler-Maclaurin error terms of the trapezoidal rule are the odd derivatives at the end points; if all of them vanish the error is smaller than every power of the step: spectral accuracy.
  5. No block length achieves 0.2 bins for all eight DTMF tones at 8 kHz up to : the best is (worst deviation bins). The classical gives bins, which is why a threshold of about bins is used in practice.

Further reading

  • G. Goertzel, “An algorithm for the evaluation of finite trigonometric series”, American Mathematical Monthly 65 (1958) 34–35.
  • L. R. Rabiner, R. W. Schafer and C. M. Rader, “The chirp z-transform algorithm”, IEEE Transactions on Audio and Electroacoustics 17 (1969) 86–92.
  • A. V. Oppenheim and R. W. Schafer, Discrete-Time Signal Processing, 3rd ed., Pearson, 2010, sections 9.2 and 9.6.