Find the dominant frequency
Compute the spectrum of a window with a DFT and report its strongest frequency. A medium embedded C problem (The FFT and frequency analysis), run and graded…
medium · The FFT and frequency analysis · dsp · dft · frequency
The DFT measures how much of each frequency a window of N samples contains. Bin k (for k from 1 to N/2) corresponds to frequency k × fs / N, and its magnitude is:
|X(k)| = √( (Σ x[n]·cos(2πkn/N))² + (Σ x[n]·sin(2πkn/N))² )
Write dominant_hz(x, n, fs): compute the magnitude of bins 1 to N/2 (skip bin 0, the DC offset), and return the frequency of the strongest bin in Hz (the lowest bin on ties).
Starter code
double dominant_hz(const double *x, int n, double fs) {
// Count zero crossings: two per period.
int crossings = 0;
for (int i = 1; i < n; i++) if ((x[i - 1] < 0) != (x[i] < 0)) crossings++;
return crossings / 2.0 * fs / n;
}Example tests
A clean tone
double x[64];
tone(x, 64, 1000, 125, 1.0, 0, 0, 0);
printf("%.1f Hz\n", dominant_hz(x, 64, 1000));Expected output:
125.0 HzTwo tones
double x[64];
tone(x, 64, 1000, 62.5, 0.4, 250, 1.0, 0);
printf("%.1f Hz\n", dominant_hz(x, 64, 1000));Expected output:
250.0 HzLearn it first
- The FFT and frequency analysis · Bins, resolution, windows and spectral leakage, and Goertzel.