Overview
Any stretch of signal can be built by adding sine waves of different frequencies, each with its own strength and timing. The Fourier transform finds that recipe. For each candidate frequency it measures how well a wave of that frequency matches the signal, and returns a complex number whose size is the strength and whose angle is the timing. The picture that results, strength against frequency, is the spectrum. Computed directly this takes multiplications for samples. The fast Fourier transform, or FFT, gets the same numbers far quicker by splitting the problem in half again and again.
A short history
Joseph Fourier claimed in 1807, and published in 1822, that functions can be written as sums of sines and cosines, in his study of heat flow. The discrete version suits sampled data but costs a number of steps that grows with the square of the length. In 1965 James Cooley and John Tukey published the fast algorithm, which made spectral analysis routine on computers. Gauss had used a similar method around 1805, unpublished in his lifetime.
How it works
- Take samples of the signal, spaced seconds apart.
- For each bin from 0 to , multiply the signal by a complex sinusoid that completes cycles over the samples, and add up the products.
- Read the result: the magnitude of bin is the strength of frequency , and its angle is the phase. Bins above are the negative frequencies.
- To compute this fast, split the samples into even-indexed and odd-indexed halves, transform each half, and combine them with one multiplication per output pair.
- Repeat the split inside each half until the pieces have length 1. For lengths that are not a power of two the template uses Bluestein's method, which turns the transform into a convolution.
- For a real signal keep the bins from 0 to and double the interior ones to get the one-sided amplitude spectrum.
Watch out for
- The transform treats the samples as one period of an endless repetition. A sine that does not complete a whole number of cycles leaks into neighbouring bins, which is why windows are used.
- Frequencies above cannot be represented. They fold back and appear as lower frequencies, an effect called aliasing that no later processing can undo.
- The spacing between bins is . Appending zeros gives more bins but no new information, so two close tones stay merged unless you record for longer.
- Scaling conventions differ between libraries. Here backward puts the factor on the inverse and ortho splits it evenly, and mixing them gives amplitudes off by or .
- The one-sided spectrum is only valid for real signals. A complex signal has unrelated content at positive and negative frequencies.
Use cases
When to use it
Finding the periodic components of a signal, designing and checking filters, computing convolutions quickly, and as the first step of almost every audio and vibration feature.
In industry
- Telecommunications
- Wi-Fi, LTE and 5G use OFDM, where the transmitter and receiver run an FFT on every symbol to split data across many subcarriers.
- Medical imaging
- MRI scanners measure data in the frequency domain and reconstruct the image with an inverse Fourier transform.
- Compression
- MP3, AAC and JPEG rely on close relatives of the Fourier transform to find components that can be stored coarsely.
- Machinery diagnostics
- Vibration analysts read the spectrum of a rotating machine to find peaks at frequencies tied to imbalance or bearing faults.
Choosing it: what must hold
- Uniformly sampled data at a known sample rate.
- Frequency content that stays roughly the same over the analysed stretch.
- A sample rate above twice the highest frequency present, so that no aliasing occurs.
- A long enough record: frequency resolution equals the sample rate divided by the number of samples.
When to choose something else
| If | Use instead |
|---|---|
| Frequency content changes over time | Spectral analysis with the short-time Fourier transform |
| Events are short and occur at several scales | Wavelets |
| The record does not hold a whole number of periods and peaks smear | Windowing before the transform |
Math foundations
Discrete Fourier transform
Bin is the inner product of the signal with a complex sinusoid that makes cycles in samples. This is what dft computes directly, at a cost of multiplications.
Inverse transform
The signal is rebuilt exactly as a sum of those sinusoids, weighted by the spectrum. Nothing is lost: the transform is a change of coordinates.
Frequency of a bin
Bin corresponds to cycles over the whole record, which lasts seconds. The spacing between bins is one over the duration of the record.
Parseval's relation
Energy is the same whether measured in time or in frequency. The method power_spectrum is scaled so that its values add up to the mean of .
The radix-2 split
and are the transforms of the even-indexed and odd-indexed samples, each of length . Two outputs come from one multiplication, for from 0 to .
Cost of the FFT
Each level of the recursion does work proportional to , and there are levels. For a million samples that is about 20 million operations where the direct sum needs a trillion.
Convolution theorem
Convolution in time is multiplication in frequency, for sequences zero-padded to the full output length. Fourier.convolve uses this to convolve two sequences with three transforms.
Symbols
- the signal at sample
- the spectrum at bin , a complex number
- the number of samples
- the sample index and the frequency bin index
- the imaginary unit
- the sample rate in Hz (sample_rate in the config)
- the frequency of bin and the spacing between bins
- the transforms of the even-indexed and odd-indexed samples
- the number of operations for a length- transform
- the convolution of sequences and
- the transforms of and
Worked by hand
Transform the four samples , which are one cycle of a cosine. With the factor equals at , and only and are non-zero.
All the energy sits in bin 1 and its mirror, bin 3, which is the negative frequency. Folding the pair together gives amplitude 1 at one cycle per four samples, and Parseval's relation checks out.
Visual example
Loading the example.
Try this
- Move the first sine from 4 Hz to 4.5 Hz. Its single tall bin turns into a spread of smaller ones.
- Raise the noise to 1 and keep only 2 bins: the rebuilt curve still shows the two sines.
- Slide the bins kept up to 33 and the rebuilt curve lands exactly on the signal.
Code sample
import numpy as np
from impl import Fourier, fft, ifft
from config import FourierConfig
sr = 1000.0
t = np.arange(1000) / sr
x = 3.0 * np.sin(2 * np.pi * 50 * t) + 1.0 * np.sin(2 * np.pi * 120 * t)
f = Fourier(FourierConfig(sample_rate=sr))
freqs, amps = f.amplitude_spectrum(x) # amps is 3.0 at 50 Hz and 1.0 at 120 Hz
f.dominant_frequency(x) # 50.0
back = ifft(fft(x)).real # equals xRead the implementation (144 lines)
"""Discrete Fourier transform, written out.
`dft` is the O(N^2) definition. `fft` is a radix-2 Cooley-Tukey FFT for lengths that are powers of two and
Bluestein's chirp-z algorithm for every other length, so it is O(N log N) for any N. `Fourier` adds the
frequency axis, one-sided amplitude and power spectra, the dominant frequency and FFT convolution.
One-dimensional signals only.
"""
from __future__ import annotations
import math
import numpy as np
try:
from .config import FourierConfig
except ImportError: # run from the template's own folder
from config import FourierConfig
def dft(x) -> np.ndarray:
"""Discrete Fourier transform by its definition: X[k] = sum_n x[n] exp(-2 pi i k n / N).
x: array (N,), real or complex. Returns complex array (N,). O(N^2): for checking and for short signals.
"""
x = np.asarray(x, dtype=complex).ravel()
n = np.arange(x.size)
return np.exp(-2j * np.pi * np.outer(n, n) / max(x.size, 1)) @ x
def _fft_power_of_two(x: np.ndarray) -> np.ndarray:
"""Recursive radix-2 Cooley-Tukey FFT. len(x) must be a power of two."""
n = x.size
if n == 1:
return x.copy()
even = _fft_power_of_two(x[0::2])
odd = _fft_power_of_two(x[1::2])
twisted = np.exp(-2j * np.pi * np.arange(n // 2) / n) * odd
return np.concatenate([even + twisted, even - twisted])
def _ifft_power_of_two(spectrum: np.ndarray) -> np.ndarray:
return np.conj(_fft_power_of_two(np.conj(spectrum))) / spectrum.size
def _fft_bluestein(x: np.ndarray) -> np.ndarray:
"""FFT of any length as a convolution with a chirp, itself computed with power-of-two FFTs."""
n = x.size
k = np.arange(n)
chirp = np.exp(-1j * np.pi * ((k * k) % (2 * n)) / n)
m = 1 << (2 * n - 1).bit_length()
a = np.zeros(m, dtype=complex)
a[:n] = x * chirp
b = np.zeros(m, dtype=complex)
b[:n] = np.conj(chirp)
b[m - n + 1:] = np.conj(chirp[1:])[::-1]
conv = _ifft_power_of_two(_fft_power_of_two(a) * _fft_power_of_two(b))
return chirp * conv[:n]
def fft(x) -> np.ndarray:
"""Fast Fourier transform of a 1-D signal of any length. Same result as `dft`, in O(N log N).
x: array (N,), real or complex. Returns complex array (N,), unscaled.
"""
x = np.asarray(x, dtype=complex).ravel()
n = x.size
if n == 0:
raise ValueError("the signal is empty")
if n & (n - 1) == 0:
return _fft_power_of_two(x)
return _fft_bluestein(x)
def ifft(spectrum) -> np.ndarray:
"""Inverse of `fft`: x[n] = (1/N) sum_k X[k] exp(+2 pi i k n / N). Returns complex array (N,)."""
spectrum = np.asarray(spectrum, dtype=complex).ravel()
return np.conj(fft(np.conj(spectrum))) / spectrum.size
class Fourier:
"""Frequency-domain view of a sampled signal."""
def __init__(self, config: FourierConfig | None = None) -> None:
self.config = config or FourierConfig()
def forward(self, x) -> np.ndarray:
"""Spectrum of x, array (N,) -> complex array (N,), scaled according to `norm`."""
spectrum = fft(x)
return spectrum / math.sqrt(spectrum.size) if self.config.norm == "ortho" else spectrum
def inverse(self, spectrum) -> np.ndarray:
"""Signal whose `forward` is the given spectrum. Returns complex array (N,)."""
x = ifft(spectrum)
return x * math.sqrt(x.size) if self.config.norm == "ortho" else x
def frequencies(self, n: int) -> np.ndarray:
"""Frequency in Hz of each of the n bins of `forward`: non-negative first, then negative."""
k = np.arange(n)
return np.where(k < (n + 1) // 2, k, k - n) * self.config.sample_rate / n
def one_sided_frequencies(self, n: int) -> np.ndarray:
"""Frequencies 0 .. sample_rate / 2 of the n // 2 + 1 non-negative bins."""
return np.arange(n // 2 + 1) * self.config.sample_rate / n
def amplitude_spectrum(self, x) -> tuple[np.ndarray, np.ndarray]:
"""One-sided amplitude spectrum of a real signal.
Returns (frequencies, amplitudes), both arrays (N // 2 + 1,). A sine A sin(2 pi f t) whose frequency
falls exactly on a bin shows up as amplitude A at f.
"""
x = np.asarray(x, dtype=float).ravel()
n = x.size
amplitude = np.abs(fft(x)[: n // 2 + 1]) / n
last = n // 2 if n % 2 == 0 else n // 2 + 1 # the Nyquist bin, present for even n, is not doubled
amplitude[1:last] *= 2.0
return self.one_sided_frequencies(n), amplitude
def power_spectrum(self, x) -> tuple[np.ndarray, np.ndarray]:
"""One-sided power per bin of a real signal; the values sum to the mean of x^2 (Parseval).
Returns (frequencies, power), both arrays (N // 2 + 1,).
"""
x = np.asarray(x, dtype=float).ravel()
n = x.size
power = np.abs(fft(x)[: n // 2 + 1]) ** 2 / n**2
last = n // 2 if n % 2 == 0 else n // 2 + 1
power[1:last] *= 2.0
return self.one_sided_frequencies(n), power
def dominant_frequency(self, x) -> float:
"""Frequency in Hz of the strongest non-constant component of a real signal."""
freqs, amplitude = self.amplitude_spectrum(x)
if amplitude.size < 2:
raise ValueError("the signal is too short to hold a frequency")
return float(freqs[1 + int(np.argmax(amplitude[1:]))])
@staticmethod
def convolve(a, b) -> np.ndarray:
"""Linear convolution of two real sequences through the frequency domain. Returns array (len(a) + len(b) - 1,)."""
a, b = np.asarray(a, dtype=float).ravel(), np.asarray(b, dtype=float).ravel()
size = a.size + b.size - 1
m = 1 << (size - 1).bit_length()
fa = fft(np.concatenate([a, np.zeros(m - a.size)]))
fb = fft(np.concatenate([b, np.zeros(m - b.size)]))
return np.real(ifft(fa * fb))[:size]- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 8, run with
python3 -m unittest -v
Practice
Check that fft([1, 0, -1, 0]) matches dft and the worked example. Then sample 3 * sin(2 pi 50 t) at 1000 Hz for exactly 1 second and call Fourier(FourierConfig(sample_rate=1000)).amplitude_spectrum and dominant_frequency. Repeat with a 50.5 Hz sine and describe what happens to the peak and its neighbours. Time dft against fft on 2048 samples.
Check on learning
- A 50.5 Hz sine recorded for exactly one second does not give a single clean peak. Why, and what would fix it without changing the frequency?
A way to think about it
Count how many cycles fit in the record. Then think about recording for two seconds, or about tapering the ends with a window.
- A 900 Hz tone is sampled at 1000 Hz. At which frequency does it show up in the spectrum, and why can you not tell it from a real tone there?
A way to think about it
Compare the samples of a 900 Hz sine with those of a 100 Hz sine at the same sample instants. The fold happens around .
- Zero-padding a 100-sample record to 1000 samples gives ten times as many bins. Does it let you separate two tones that are 5 Hz apart at a 1000 Hz sample rate?
A way to think about it
The true resolution is set by how long you observed, here a tenth of a second. Extra bins interpolate the same blurred curve.
- Why does the amplitude spectrum double the interior bins but not bin 0 or the Nyquist bin?
A way to think about it
A real sinusoid splits its energy between a positive and a negative frequency bin. Ask which bins have no separate mirror image.
- When is computing a convolution through the FFT faster than doing it directly, and when is it not worth it?
A way to think about it
Compare the direct cost, the product of the two lengths, with the cost of three transforms. Consider one very short sequence.