Sampling at 4,096 Hz for 1,024 samples gives an FFT bin spacing of 4 Hz. A 401.4 Hz sinusoid produces its largest bin at 400 Hz. The neighboring bins still carry information about where the peak lies between samples of the spectrum.
This article estimates the frequency of an isolated stationary tone. For amplitude measurements, see FFT amplitude scaling . The FFT introduction covers the transform and frequency axis.
Why the peak falls between bins
Window \(N\) measured samples and use an FFT of length \(M\) . Bin \(k\) then represents \(f_k=kf_s/M\) . Windowing a sinusoid creates a main lobe. When the frequency falls between bins, the magnitudes on either side of the largest bin differ. That asymmetry indicates which side the center of the lobe is on.
Padding to four times the input length reduces the grid spacing from 4 Hz to 1 Hz in this example. Apply the window to the original 1,024 samples before padding. The observation still lasts 0.25 seconds, and the main lobe has the same width in hertz. Grid spacing, single-tone estimation error, and the ability to resolve two different tones measure different things.
Fit a parabola to three log magnitudes
Let \(k\) be the largest bin and let \(a,b,c\) denote the log magnitudes to its left, at its center, and to its right. With \(u\) measuring the offset from bin \(k\) , the parabola through \(u=-1,0,1\) is
\[ q(u)=b+\frac{c-a}{2}u+\frac{a-2b+c}{2}u^2. \]Solving \(q'(u)=0\) gives the offset and the frequency estimate:
\[ \delta=\frac{1}{2}\frac{a-c}{a-2b+c},\qquad \hat{f}=(k+\delta)\frac{f_s}{M}. \]When the right neighbor has greater magnitude than the left, the numerator and denominator are both negative, giving a positive offset. Equal neighbors give zero offset. The example uses natural logarithms. Switching to decibels multiplies all three values by the same factor and leaves the ratio unchanged. The parabola approximates the log magnitude near the top of the Hann main lobe. Its accuracy depends on the window and the frequency offset. Abe and Smith’s study of quadratic peak interpolation discusses this bias.
Compare the largest bin and interpolation with NumPy
np.hanning(N + 1)[:-1] gives a periodic Hann window. The
SciPy Hann window documentation
explains the distinction between periodic and symmetric windows. The function removes the mean, applies the window, and takes the maximum over all bins of the real FFT. It assumes the tone of interest dominates the spectrum.
import numpy as np
def peak_frequency(x, fs, pad=1, interpolate=True):
x = np.asarray(x)
if x.ndim != 1 or x.size < 8 or not np.isrealobj(x):
raise ValueError("x must be a real vector with at least 8 samples")
if not np.all(np.isfinite(x)) or not np.isfinite(fs) or fs <= 0:
raise ValueError("samples must be finite and fs must be positive and finite")
if isinstance(pad, bool) or not isinstance(pad, (int, np.integer)) or pad < 1:
raise ValueError("pad must be a positive integer")
n = x.size
m = n * pad
window = np.hanning(n + 1)[:-1] # periodic Hann
magnitude = np.abs(np.fft.rfft((x - x.mean()) * window, n=m))
k = int(np.argmax(magnitude))
if not 1 <= k < magnitude.size - 1 or magnitude[k] == 0:
raise ValueError("no nonzero interior peak with two neighbors")
if not interpolate:
return k * fs / m
left, center, right = magnitude[k - 1 : k + 2]
if left <= 0 or right <= 0:
raise ValueError("log interpolation requires three positive magnitudes")
a, b, c = np.log([left, center, right])
curvature = a - 2 * b + c
if curvature >= 0:
raise ValueError("local peak has no negative curvature")
offset = 0.5 * (a - c) / curvature
return (k + offset) * fs / m
fs, n = 4096, 1024
t = np.arange(n) / fs
f0 = 401.4
x = np.cos(2 * np.pi * f0 * t + 0.4)
methods = [(1, False), (1, True), (4, False), (4, True)]
for pad, interp in methods:
estimate = peak_frequency(x, fs, pad=pad, interpolate=interp)
print(f"{pad=}, {interp=}: {estimate:.6f} Hz, error {estimate - f0:+.6f} Hz")
# Sweep several fractional offsets around the same bin.
tones = 400 + np.linspace(-0.49, 0.49, 99) * (fs / n)
for pad, interp in methods:
errors = []
for f in tones:
x = np.cos(2 * np.pi * f * t + 0.4)
errors.append(peak_frequency(x, fs, pad, interp) - f)
print(f"{pad=}, {interp=}: max absolute error {np.max(np.abs(errors)):.6f} Hz")
# Two tones within one original bin can yield one blended maximum.
x = np.cos(2 * np.pi * 400 * t) + np.cos(2 * np.pi * 402 * t)
print(f"Two tones, blended peak: {peak_frequency(x, fs, pad=16):.6f} Hz")
For the first tone, the signed error is the estimate minus the true frequency.
| Method | Estimated frequency | Error |
|---|---|---|
| No padding, largest bin | 400.000000 Hz | −1.400000 Hz |
| No padding, interpolation | 401.459789 Hz | +0.059789 Hz |
| 4× FFT length, largest bin | 401.000000 Hz | −0.400000 Hz |
| 4× FFT length, interpolation | 401.400582 Hz | +0.000582 Hz |
Over 99 tones from −0.49 to +0.49 bins around 400 Hz, the largest absolute errors in the same order were approximately 1.960, 0.0640, 0.480, and 0.000778 Hz. Padding brings the three points closer to the peak, so the fitted parabola covers a smaller part of the lobe. These numbers come from noise-free tones around 400 Hz with phase 0.4 radians. Real measurements also depend on sample-clock accuracy and the signal conditions.
A peak at 401 Hz can come from tones at 400 and 402 Hz
The final example adds equal-amplitude tones at 400 Hz and 402 Hz. Both start at phase zero. Even with 16× padding and interpolation, the function returns a peak at about 401 Hz. The windowed spectra of the two tones overlap to produce this peak, so its center corresponds to neither tone.
When applying the method to measured data:
- Choose the frequency band and observation time for the signal you want to track. If you restrict the peak search to a band, keep the original array for finding the adjacent bins.
- Expect special behavior near DC and Nyquist. Mean removal and overlap between positive- and negative-frequency components can distort those peaks. The example raises an error at either endpoint, where two neighbors are unavailable.
- To separate nearby stationary tones, collect more actual samples and compare the window’s main-lobe width with the spacing of the tones. For tones that move over time, see practical spectrogram design .
FAQ
Can I estimate frequencies more precisely than the FFT bin spacing?
For an isolated stationary sinusoid, the peak bin and its neighbors can locate the frequency between bins. Accuracy depends on noise, nearby components, and frequency drift.
Can zero padding separate two close frequencies?
Zero padding samples the same finite windowed spectrum on a denser grid. The observation time and main-lobe width stay the same, so two overlapping components may still produce one peak.
When does log-parabolic interpolation fail?
There are no two neighbors at the endpoints of a one-sided FFT, and the logarithm is undefined when one of the three magnitudes is zero. A peak formed by nearby components also violates the single-tone assumption.