DSP Explorables
The Fourier transform
The Fourier transform takes a signal and tells you how much of each frequency it contains. It’s behind almost everything else on this site: frequency responses, filter design, MP3’s psychoacoustic model, and spectrograms. Its formula looks forbidding:
By the end of this page every symbol in it should make sense, as should why it works and how the FFT computes it so quickly. We’ll start from scratch with a picture of complex numbers as arrows.
1 · Arrows that spin
Section titled “1 · Arrows that spin”Complex numbers are arrows
Section titled “Complex numbers are arrows”A complex number such as is just a point on a flat plane: 3 along the horizontal (real) axis, 2 up the vertical (imaginary) axis. Think of it as an arrow from the centre to that point. (Engineers write for ; mathematicians write , but in electronics already means current.)
Arrows give complex arithmetic a picture. Pick each one in the figure below:
- Adding two complex numbers adds their “along” parts and their “up” parts. As arrows: put the second arrow’s tail on the first one’s tip.
- Every arrow has a size (its length, written ) and an angle (measured anticlockwise from the positive real axis, written ). The next subsection shows how to work them out.
- Multiplying two complex numbers multiplies their sizes and adds their angles. That’s the key fact. You can check it by multiplying out the brackets the ordinary way, using ; the figure shows the working.
- itself is the arrow of size 1 pointing straight up (90°), so multiplying by turns any arrow a quarter-turn anticlockwise. Do it twice and you’ve turned 180°, which is why .
- More generally, multiplying by an arrow of size 1 just rotates whatever it multiplies.
The complex plane. 3 + 2j as a point: 3 along, 2 up. Adding: the green arrow is what you get by walking along and then along . Size and angle: the arrow’s length (by Pythagoras) and direction. Multiplying: the green product’s length is the two lengths multiplied, and its angle is the two angles added; the working is printed underneath. Multiplying by j: four quarter-turns bring you back to the start. Drag the dots to try your own numbers.
From an angle to a point: SOH CAH TOA
Section titled “From an angle to a point: SOH CAH TOA”Here’s the one piece of school trigonometry everything else on this page rests on. In a right-angled triangle, pick one of the other two angles and call it . The longest side is the hypotenuse, the side touching is the adjacent side, and the side across from it is the opposite side. The three trig functions are just ratios of these sides, remembered as SOH CAH TOA:
Now draw an arrow of length 1 at angle , and drop a line straight down from its tip to the horizontal axis. That makes a right-angled triangle whose hypotenuse is the arrow (length 1), whose adjacent side is how far across the tip is, and whose opposite side is how far up it is. So:
- CAH: across
- SOH: up
The arrow of length 1 at angle ends at the point : it’s the complex number . (An arrow of length is just times that.)
Top: the arrow of length 1 at angle , with its triangle: across (blue), up (orange), and the arrow itself as the hypotenuse. Bottom: across and up for every angle, which are the cosine and sine curves. Drag the angle past 90°. The tip moves left of centre, so “across” becomes negative. Past 180° “up” goes negative too. The triangle definitions only make sense up to 90°, so cos and sin are defined this way all the way round, signs included. That’s why they keep going as waves.
Going the other way, from a point to its size and angle, uses the same triangle. The size is the
hypotenuse, by Pythagoras: . The angle comes from TOA: .
(Calculators and code use a function called atan2(b, a), which also works out which way round the
arrow points.)
The arrow at angle θ, and why it’s written
Section titled “The arrow at angle θ, and why it’s written ejθe^{j\theta}ejθ”So the arrow of size 1 at angle is , and multiplying two of these adds their angles. Exponents behave the same way: . Because angles add when you multiply, the angle behaves like an exponent, and that’s why this arrow is written
That’s Euler’s formula. It isn’t just a convenient label: it really is the number raised to the power . Here’s why.
A side trip: Euler’s identity, as compound interest
Section titled “A side trip: Euler’s identity, as compound interest”The number comes from compound interest. Suppose a bank pays 100 % interest a year. Paid all at once at the end of the year, 1 pound becomes 2. Paid in two halves of 50 %, the second payment also earns interest on the first: 1 × 1.5 × 1.5 = 2.25 pounds. Paid monthly, it’s . The more often interest is paid, the more you end up with, but the total doesn’t grow without limit:
| payments per year, | |
|---|---|
| 1 | 2 |
| 2 | 2.25 |
| 4 | 2.441406 |
| 12 (monthly) | 2.613035 |
| 365 (daily) | 2.714567 |
| 1,000 | 2.716924 |
| 10,000 | 2.718146 |
| 1,000,000 | 2.718280 |
It homes in on 2.718281…, and that limit is the number . At a different rate it works the same way, and gives :
So what is ? Use the same recipe with : grow by , times. Multiplying by means “keep what you have, and add a small piece times as long, turned 90°” (multiplying by is a quarter-turn). A small push at right angles is a small rotation. So each step turns the arrow by about without changing its length much, and steps turn it by in total.
The path of , one step at a time. Each step adds a small piece at right angles to the current arrow. With few steps the path cuts corners and spirals outwards. As grows, the steps get smaller and the path hugs the unit circle, landing on (green). Set the angle to π (180°) and the path ends at −1:
That’s Euler’s identity, often called the most beautiful equation in mathematics. It ties together , , , 1 and 0.
Spinning arrows are sinusoids
Section titled “Spinning arrows are sinusoids”Now let the angle grow steadily, by radians every sample: for The arrow spins. Its horizontal shadow is and its vertical shadow is : a sinusoid is the shadow of a spinning arrow.
Left: the arrow , with dots where it pointed at earlier samples, and its two shadows. Right: the shadows over time, a cosine and a sine. A positive speed spins anticlockwise and a negative one clockwise. Those are negative frequencies, which turn out to be just as real as positive ones. Tick the last box: add an arrow spinning the other way, , and average the two. The vertical parts cancel, and what’s left is a real cosine:
Every real sinusoid is a pair of arrows spinning in opposite directions. (This is the same fact the MP3 page uses to shift filters up in frequency.)
This also explains a phrase used on the filter pages: “delaying by one sample multiplies by ”. A spinning arrow one sample ago pointed radians further back. Turning it back by means multiplying by the arrow at angle , which is .
2 · Why sinusoids?
Section titled “2 · Why sinusoids?”Why break signals into sinusoids, rather than square waves or anything else? Three reasons.
Filters can’t change them. Feed a spinning arrow into any filter that only delays, scales and adds (an FIR or IIR filter, an echo, a room). Each delayed copy is the same arrow, rotated. Each scaled copy is the same arrow, stretched. Adding rotated, stretched copies of one arrow gives one arrow, rotated and stretched. So out comes the same spinning arrow, multiplied by a single complex number:
That number is the frequency response. No other shape survives a filter intact. Put a square wave through a low-pass filter and it comes out rounded. So if a signal is written as a sum of sinusoids, filtering it is simple: multiply each sinusoid by its own .
Nature uses them. Strings, air columns and circuits vibrate in sinusoids, and the inner ear separates sound into frequencies before your brain hears it.
Anything can be built from them. Fourier’s bold claim (1807) was that any repeating signal is a sum of sinusoids at whole multiples of its repetition frequency.
Top: the ingredients: sinusoids at 1, 3, 5… times the basic frequency. Middle: their sum, approaching the target as you add harmonics. Bottom: the recipe: how much of each harmonic. A square wave needs only the odd harmonics, at 1, 1/3, 1/5… of the first; a triangle’s fall away much faster (), because it has no sharp edges. The overshoot at the square’s edges never disappears, however many harmonics you add. That’s the Gibbs phenomenon from the FIR page, seen from the other side.
That bottom panel is the idea of a spectrum. Building a signal from a recipe is synthesis. The Fourier transform does the reverse, analysis: given the signal, find the recipe.
3 · Measuring “how much”: multiply and add
Section titled “3 · Measuring “how much”: multiply and add”How do you find how much of one particular frequency is hiding in a signal? Multiply the signal by a test wave at that frequency, sample by sample, and add up the results.
If the signal contains the test frequency, the two rise and fall together. Their products are mostly positive, and the sum grows big. If it doesn’t, the products swing between positive and negative and cancel out. Dividing the sum by turns it into the amplitude of that component. (This multiply-and-add is called a correlation, or a dot product.)
Left: the result. Right: the signal and test wave, and their product sample by sample (blue positive, red negative). Set the test frequency to 3 and the products are almost all positive: the result is 1, the amplitude of that component. At 7 it finds 0.5. At 5 there’s nothing, and everything cancels.
Now pick a sine at 5 cycles and test at 5 with a cosine only. The test finds nothing, even though the signal is a perfect 5-cycle wave! A sine and a cosine at the same frequency are a quarter-cycle apart, so their product is positive half the time and negative half the time. Drag Shift the signal to see the cosine-only result slide between −1 and 1. A single test wave measures “how much is in step with me”, which depends on the phase.
The fix is to test with two waves, a cosine and a sine. Any sinusoid at that frequency, whatever its phase, is a mixture of the two. The two results say how much of each, so together they give the amplitude (the length of the arrow, ) and the phase (its angle). Switch the figure to a cosine and a sine: now the amplitude stays at 1 however you shift the signal, and only the arrow’s angle turns.
A pair of numbers that belong together is a complex number, so do both tests at once: multiply by , which is :
There’s a lovely way to picture this. The component of the signal at frequency is a spinning arrow. Multiplying by spins it backwards at the same speed, so it stops spinning, and adding up all samples piles copies of it end to end. Components at any other frequency are still spinning after the multiplication, so they go round in circles and add up to (nearly) nothing.
4 · Orthogonality: why each test only sees its own frequency
Section titled “4 · Orthogonality: why each test only sees its own frequency”That cancellation is exact when the frequencies are whole numbers of cycles across the window. Multiply two different whole-cycle sinusoids and the products always sum to precisely zero. Mathematicians call such signals orthogonal.
The word comes from geometry. Think of 16 samples as a single arrow in 16-dimensional space: one coordinate per sample. The multiply-and-add is the dot product, which measures how much two arrows point the same way, and it’s zero for arrows at right angles. With 16 samples there happen to be exactly 16 whole-cycle sinusoids: cosines with 0 to 8 cycles and sines with 1 to 7. All 16 are at right angles to each other, like 16 perpendicular axes.
Top: the dot product of every pair of those 16 sinusoids (rows and columns in the same order), each normalised so a sinusoid with itself scores 1. Only the diagonal is filled in: every different pair scores zero. Click a square to see that pair below: the two sinusoids, and their product sample by sample. The positive and negative products cancel perfectly. Then tick the box to give B a non-whole number of cycles. The cancellation fails, and the test now responds to a frequency that isn’t its own. That’s leakage, and section 7 comes back to it.
Perpendicular axes are what make coordinates easy. Because the axes are perpendicular, the “how far along x” measurement isn’t disturbed by how far along y something is. In the same way, any 16-sample signal is exactly one combination of those 16 sinusoids, and each test measures its own ingredient without interference from the others.
5 · The discrete Fourier transform
Section titled “5 · The discrete Fourier transform”Now do the test for every frequency that fits a whole number of cycles into the samples: cycles, for . Testing for cycles means turning by per sample. That’s the discrete Fourier transform (DFT), and the formula at the top of the page:
In words: for each bin , spin the signal backwards at turns per window, and add it up. Each is a complex number. Its size says how much of that frequency there is, and its angle the phase.
Top: the signal, with the test wave for the selected bin (its real part, dashed). Middle: the size of every . Bottom: the angles. Try the presets. Two cosines give two spikes (plus mirror images). A single impulse contains every frequency equally. A constant shows up only in bin 0. A cosine at 5.5 cycles, between two bins, leaks into all of them. Noise spreads everywhere.
A few things to notice about the bins:
- Bin is the frequency cycles per sample, or Hz. The spacing between bins, the frequency resolution, is . A longer window gives finer resolution.
- Bins above are negative frequencies. turns per window forwards looks exactly the same, sample by sample, as turns backwards, since the samples can’t tell a full extra turn. (This is aliasing, explored properly on the sampling page.) For a real signal, each cosine is a pair of opposite spinning arrows (section 1), so it shows up twice: at and at , with half its strength in each. That’s the mirror image in the middle panel.
- Bin 0 is the average (the “DC” part), and bin is the Nyquist frequency.
6 · Going back: the inverse transform
Section titled “6 · Going back: the inverse transform”Spinning the arrows back up
Section titled “Spinning the arrows back up”The DFT turns samples into arrows. Can we turn them back into the signal? Yes, and the way back is almost the same calculation:
Compare it with the forward transform. Only two things differ: the sign in the exponent, and the in front.
The sign. The forward transform multiplied by to un-spin the component at frequency , so it stood still and piled up. Going back, each arrow has to be set spinning again, in the original direction. That’s multiplying by . Then add up all the spinning arrows.
The 1/N. When the forward transform un-spun a component, adding up samples piled copies of its arrow end to end. So is times bigger than the arrow actually in the signal, and the inverse divides by to undo that. You’ve seen this already. The DFT explorer’s cosine of amplitude 1 read 32 in its bin. A cosine is two arrows of length ½ (section 1), and with , . (Some books split the factor evenly instead, putting on both transforms. That’s a convention; it changes nothing important.)
Why so symmetric? It’s the perpendicular axes from section 4 again. To find a point’s coordinates in 3-D, you measure how far it goes along each axis: a dot product with each axis. To rebuild the point from its coordinates, you go that far along each axis and add up. Both directions use the same axes; one measures along them, the other builds along them. The only wrinkle is that our “axes”, the test waves, aren’t of length 1. Each one’s dot product with itself is , not 1, and that’s the same factor of again.
A real signal, rebuilt from spinning arrows
Section titled “A real signal, rebuilt from spinning arrows”So each bin contributes an arrow of length , starting at angle , and spinning turns every samples. Bins above count as negative frequencies, spinning the other way. Chain the arrows tip to tail, set them all spinning, and the tip of the last one traces out the signal. Ancient astronomers used chains of circles like this, called epicycles, to model the planets.
For a real signal, the arrows come in mirror-image pairs. Bin and bin (that is, ) have the same length and opposite angles, and spin in opposite directions. So their vertical parts always cancel, which is exactly the “a cosine is two opposite arrows” picture from section 1. Whatever the arrows do, the tip stays on the horizontal axis, sliding back and forth, and its position over time is the signal.
Left: the chain of arrows at the current time. Bin 0 (black) is a constant offset, each arrow (blue) has a partner (orange), and the tip (green) stays on the horizontal axis. Right: where the tip has been, the blue curve, against the original samples. Below, which arrows are in use. Press Play and watch the pairs turn in opposite directions. Add frequencies one pair at a time. The two sinusoids signal is complete after five pairs, and adding more contributes nothing, because those arrows have zero length. The square wave sharpens with every odd pair. The blue curve also fills in between the samples: the arrows keep turning between sample times, which gives a smooth curve through every sample.
Any closed shape, drawn with arrows
Section titled “Any closed shape, drawn with arrows”Now drop the requirement that the signal is real. Let each “sample” be a complex number, a point anywhere on the plane. There’s nothing to stop the DFT working on complex samples. The only difference is that the arrows no longer need to come in mirror pairs. Without the pairs, the tip is free to leave the horizontal axis and roam the whole plane.
So take any closed outline, a heart or a star or your own scribble, and walk round it at a steady pace, noting where you are every step: across up. That’s a list of complex numbers, and because the outline is closed it repeats, trip after trip, like a periodic signal. Take its DFT, and the arrows will redraw it. Fourier’s claim from section 2 applies, so any closed shape can be drawn this way. With sample points, arrows reproduce all points exactly.
It helps to think about what each frequency contributes, adding them in order:
- Frequency 0 doesn’t turn at all. It’s the centre of the shape (the average position).
- Frequency +1 goes round exactly once per trip, anticlockwise: a circle, the roughest possible one-loop sketch. Adding −1, which goes round once clockwise, squashes that circle into the best-fitting ellipse.
- ±2, ±3, … go round 2, 3… times per trip. Riding on top of the bigger arrows, they add 2, 3… wiggles per trip: finer and finer detail, just as higher harmonics add sharpness to a sound.
- Sharp corners need a lot of high frequencies, like the square wave’s edges. Leave them out and corners come out rounded, with small ripples nearby. That’s the Gibbs phenomenon once more, in two dimensions.
A shape of 256 points, turned into 256 spinning arrows and redrawn by chaining them together. With Order: by frequency, step Arrows used up from 1: a dot at the centre; then a circle; then an ellipse; then ever finer detail as each new frequency adds its wiggles. The heart’s formula only contains frequencies from −4 to +4, so it’s exact after 9 arrows, and every arrow beyond that has zero length. (Its biggest arrow is −1, because the heart is traced clockwise.) The star’s sharp points need many more. Switch to biggest first and the same shape appears with fewer arrows, since a few large ones carry most of the outline. Keeping only the biggest coefficients and dropping the rest is the core idea of lossy compression (MP3 and JPEG do a cleverer version of it). Draw your own shape with the mouse or a finger.
7 · Leakage, windows and zero-padding
Section titled “7 · Leakage, windows and zero-padding”The DFT only tests whole-cycle frequencies. What happens to a frequency in between? Its sinusoid isn’t orthogonal to any of the test waves (section 4), so every bin responds a little: the energy leaks across the whole spectrum.
There’s a neat way to see why. Taking samples is the same as multiplying an endless signal by a rectangular window. So the DFT doesn’t see a pure sinusoid. It sees the window’s spectrum, centred on the sinusoid’s frequency, exactly the picture from the windows section of the FIR page. When the frequency is a whole number of cycles, the bins happen to land exactly on that spectrum’s zeros, and everything looks clean. Otherwise they land on its sidelobes.
Top: the samples (multiplied by the window, if one is chosen). Bottom: the DFT bins (blue), sampling the underlying continuous spectrum (grey). Start at 5.00 cycles: one clean spike, because every other bin sits on a zero. Slide to 5.5 and the energy smears across every bin, falling off only slowly (−13 dB sidelobes). Choose Hann or Blackman: the sidelobes drop dramatically, at the cost of a wider peak. It’s the same trade-off as in FIR design. Then try zero-padding: appending zeros evaluates more points on the same grey curve. It interpolates; it doesn’t sharpen the peak or separate close frequencies. Only a longer window of real signal does that.
The convolution theorem, briefly
Section titled “The convolution theorem, briefly”One more property explains why the Fourier transform is so central. Filtering in time is multiplication in frequency: the spectrum of a filter’s output is the input’s spectrum times the filter’s frequency response. That’s why the FIR page could get a filter’s frequency response from the FFT of its taps. It’s also why long filters are often run by transforming the signal, multiplying, and transforming back. With the FFT, that’s faster than computing the convolution sum directly. (With the DFT there’s a catch: the convolution wraps around the end of the window, so in practice the signals are zero-padded first.)
8 · The FFT: the same answer, much faster
Section titled “8 · The FFT: the same answer, much faster”The DFT as written does multiply-adds for each of bins: in total. For that’s over a million. The fast Fourier transform (FFT) gets the identical answer with about “butterflies”, about 5000 for . It isn’t an approximation: it just stops repeating work. Here’s how, built up from the smallest case.
One sample. The DFT of a single sample is that sample: .
Two samples. With the test waves are , and only two values ever come up: 1 (for or equal to 0) and (for , Euler’s identity again!). So
A sum and a difference. Drawn as a diagram, the two crossing lines look like a butterfly’s wings, so this is called a butterfly.
Bigger sizes: split into even and odd samples. Split the DFT’s sum into the even-numbered samples and the odd-numbered ones. For the even samples, , the test wave is . That’s exactly an -point DFT of the even samples; call its result . The odd samples, , are the same thing shifted by one sample, and a one-sample shift multiplies by (section 1, once more). So with the -point DFT of the odd samples:
is called the twiddle factor. Now the saving. and are -point transforms, so their values repeat after bins. And jumping by turns by half a circle, which flips its sign. So the second half of the outputs comes free:
That’s a butterfly again: one multiplication by , then a sum and a difference, giving two outputs. Now split and the same way, and keep going until everything is 1-point DFTs. Each split level is one stage of butterflies, and there are levels.
An -point FFT, one stage per click. Each circle is a complex number drawn as an arrow, with its value underneath. (Arrows are scaled within each column; the numbers grow from stage to stage.) Inputs come in on the left, outputs leave on the right. Each pair of crossing lines is a butterfly. Its lower input is multiplied by the twiddle factor (), then the pair is added (top output) and subtracted (bottom output, marked −). Start with : one butterfly, a sum and a difference. Then and . Try the inputs too. An impulse at 0 gives every output the same value, since it contains all frequencies equally. An impulse at 1 gives arrows that turn by one step more at each successive bin, the one-sample delay again. The inputs are listed in a scrambled order because splitting into evens and odds repeatedly sorts sample to the row given by reversing the bits of : , binary 001, goes to row 4, binary 100.
The inverse FFT is the same algorithm with the twiddle factors spinning the other way (), and a division by at the end.
9 · Where this goes next
Section titled “9 · Where this goes next”The DFT treats its samples as the whole story. Real signals change over time, so in practice you take the DFT of short, overlapping, windowed chunks. That’s the short-time Fourier transform, and plotting its results gives a spectrogram. MP3’s psychoacoustic model does exactly that with 1024-point FFTs. The same “one bin per frequency” idea, run backwards, is how modern radio (Wi-Fi, 4G, 5G) packs data into hundreds of narrow sub-carriers (OFDM), a topic for the communications pages to come.
Further reading
Section titled “Further reading”- 3Blue1Brown, But what is the Fourier Transform? A visual introduction: the “winding around a circle” picture, beautifully animated.
- Julius O. Smith III, Mathematics of the Discrete Fourier Transform: a free online book that takes the DFT from complex numbers up.
- Steven W. Smith, The Scientist and Engineer’s Guide to Digital Signal Processing: free, practical, and light on maths.
- J. W. Cooley and J. W. Tukey, “An algorithm for the machine calculation of complex Fourier series” (1965): the paper that made the FFT famous (Gauss had found it in 1805).