Sign in

Fourier

Discrete Fourier transform and fast Fourier transform

Rewrites a sampled signal as a sum of sinusoids, with the discrete Fourier transform and the fast algorithm that computes it in Nlog⁡NN \log N steps.

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 N2N^{2} multiplications for NN 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

  1. Take NN samples of the signal, spaced 1/fs1 / f_s seconds apart.
  2. For each bin kk from 0 to N−1N - 1, multiply the signal by a complex sinusoid that completes kk cycles over the NN samples, and add up the products.
  3. Read the result: the magnitude of bin kk is the strength of frequency kfs/Nk f_s / N, and its angle is the phase. Bins above N/2N/2 are the negative frequencies.
  4. 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.
  5. 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.
  6. For a real signal keep the bins from 0 to N/2N/2 and double the interior ones to get the one-sided amplitude spectrum.

Watch out for

  • The transform treats the NN 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 fs/2f_s / 2 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 fs/Nf_s / N. 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 1/N1/N on the inverse and ortho splits it evenly, and mixing them gives amplitudes off by NN or N\sqrt{N}.
  • 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

IfUse instead
Frequency content changes over timeSpectral analysis with the short-time Fourier transform
Events are short and occur at several scalesWavelets
The record does not hold a whole number of periods and peaks smearWindowing before the transform

Math foundations

  1. Discrete Fourier transform

    X[k]=∑n=0N−1x[n] e−2πikn/N,k=0,1,…,N−1X[k] = \sum_{n=0}^{N-1} x[n]\,e^{-2\pi i k n / N}, \qquad k = 0, 1, \dots, N - 1

    Bin kk is the inner product of the signal with a complex sinusoid that makes kk cycles in NN samples. This is what dft computes directly, at a cost of N2N^{2} multiplications.

  2. Inverse transform

    x[n]=1N∑k=0N−1X[k] e+2πikn/Nx[n] = \frac{1}{N}\sum_{k=0}^{N-1} X[k]\,e^{+2\pi i k n / N}

    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.

  3. Frequency of a bin

    fk=k fsN,Δf=fsNf_k = \frac{k\,f_s}{N}, \qquad \Delta f = \frac{f_s}{N}

    Bin kk corresponds to kk cycles over the whole record, which lasts N/fsN / f_s seconds. The spacing between bins is one over the duration of the record.

  4. Parseval's relation

    ∑n=0N−1∣x[n]∣2=1N∑k=0N−1∣X[k]∣2\sum_{n=0}^{N-1} |x[n]|^{2} = \frac{1}{N}\sum_{k=0}^{N-1} |X[k]|^{2}

    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 x2x^{2}.

  5. The radix-2 split

    X[k]=E[k]+e−2πik/N O[k],X[k+N2]=E[k]−e−2πik/N O[k]X[k] = E[k] + e^{-2\pi i k / N}\,O[k], \qquad X[k + \tfrac{N}{2}] = E[k] - e^{-2\pi i k / N}\,O[k]

    EE and OO are the transforms of the even-indexed and odd-indexed samples, each of length N/2N/2. Two outputs come from one multiplication, for kk from 0 to N/2−1N/2 - 1.

  6. Cost of the FFT

    T(N)=2 T ⁣(N2)+O(N) ⟹ T(N)=O(Nlog⁡N)T(N) = 2\,T\!\left(\tfrac{N}{2}\right) + O(N) \ \Longrightarrow\ T(N) = O(N \log N)

    Each level of the recursion does work proportional to NN, and there are log⁡2N\log_2 N levels. For a million samples that is about 20 million operations where the direct sum needs a trillion.

  7. Convolution theorem

    F{a∗b}[k]=A[k] B[k]\mathcal{F}\{a * b\}[k] = A[k]\,B[k]

    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

x[n]x[n]
the signal at sample nn
X[k]X[k]
the spectrum at bin kk, a complex number
NN
the number of samples
n, kn,\ k
the sample index and the frequency bin index
ii
the imaginary unit
fsf_s
the sample rate in Hz (sample_rate in the config)
fk, Δff_k,\ \Delta f
the frequency of bin kk and the spacing between bins
E[k], O[k]E[k],\ O[k]
the transforms of the even-indexed and odd-indexed samples
T(N)T(N)
the number of operations for a length-NN transform
a∗ba * b
the convolution of sequences aa and bb
A[k], B[k]A[k],\ B[k]
the transforms of aa and bb

Worked by hand

Transform the four samples x=(1,0,−1,0)x = (1, 0, -1, 0), which are one cycle of a cosine. With N=4N = 4 the factor e−2πikn/4e^{-2\pi i k n / 4} equals (−1)k(-1)^{k} at n=2n = 2, and only n=0n = 0 and n=2n = 2 are non-zero.

X[k]=1×1+(−1)×(−1)k=1−(−1)kX[k] = 1 \times 1 + (-1) \times (-1)^{k} = 1 - (-1)^{k}
X=(0, 2, 0, 2)X = (0,\ 2,\ 0,\ 2)
amplitude at bin 1=2 ∣X[1]∣N=2×24=1\text{amplitude at bin 1} = \frac{2\,|X[1]|}{N} = \frac{2 \times 2}{4} = 1
∑nx[n]2=2,14(02+22+02+22)=2\sum_{n} x[n]^{2} = 2, \qquad \frac{1}{4}\big(0^{2} + 2^{2} + 0^{2} + 2^{2}\big) = 2

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 x
Read 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

  1. 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.

  2. 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 fs/2f_s / 2.

  3. 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.

  4. 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.

  5. 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.