1. Home
  2. Explore
  3. Mathematics
  4. Fast Fourier Transform

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Fast Fourier Transform

Transcript

I want to start this video off by giving you an example of a trick you've probably done without even thinking about it. Someone plays a chord on a guitar, you hold up your phone, and some music app tells you right away: that's a C, an E and a G. But think about what your phone actually got. It didn't get notes. It got a microphone measuring air pressure, tens of thousands of times a second. Basically one long, wiggly list of numbers. Those three notes are hiding somewhere inside that wiggle, and the phone pulls them back out, many times a second, on a device running off a battery. And there's a tool or more specifically an algorithm that's working its magic behind all of this. Hello everyone. Today we're going to learn the Fast Fourier Transform.

The FFT is one of those algorithms which shows up on pretty much every list of the most important algorithms of the twentieth century, and it's one of my favourite algorithms personally. It's an algorithm that's not only useful but also has genuine beauty behind why it works. Now, the Fourier transform itself isn't new. Fourier actually wrote it down over two hundred years ago. The problem was never the math—it was just how much work it took to get to the solution The straightforward way to go about finding which frequencies are hiding in a signal is something like this: pick one frequency, test the whole signal against that frequency… then do the same thing for the next frequency… and the next… and the next. That's exactly the idea of the discrete fourier transform, or the DFT for short. Now the DFT already achieves what we wanted to do, why even bother making it fast? Think about what happens when the signal gets longer. It's worse in two ways at once.

Every single test takes longer, and there are more frequencies you have to check. So the work grows, and as you can guess, in kind of an O(n^2) fashion, we will see this concretely in a grid format later in this part Now what does the FFT offer? The FFT gives you the exact same answer, but it's way smarter about it. It notices that all those tests overlap, so instead of starting from scratch every time, it shares the work between them. That's the difference between your phone naming

that chord instantly rather than being stuck on a loading bar. And this idea is actually older than computers. Gauss was already using a version of it around 1805 to figure out the orbits of asteroids—he just never published it. Cooley and Tukey rediscovered it in 1965, right when computers finally needed it. And that algorithm, the one Gauss found first and Cooley and Tukey brought back, is exactly what we're going to learn today, split into three parts.

first part, we are going to set up some tools, complex numbers that spin, the DFT itself, and the one trick that makes it fast, which is splitting the problem into even and odd pieces. the middle part, that trick gets turned into an actual algorithm: recursion butterflies bit reversal, and a loop you could code up tonight. And in the last part, we worked through a full example by hand, flipped the whole algorithm around, and looked at where the FFT shows up in real life.

But before any of that, let me show you something that should light up those nerd neurons of yours. Take a look at this signal. This is what a recording looks like when you zoom in. It's jagged, it's all over the place, and there's no obvious pattern. If I asked you to describe it, you'd probably just give up. But watch what happens when I tilt the view. That messy line was never one thing. It's a bunch of pure waves stacked up, each one going at its own steady rate, all added together. From the front, all you see is the total. From the side, you can see every piece separately,

and how much of each there is. That side view is what we call the spectrum, and getting from the front view to the side view is exactly what a Fourier transform does. Now each of those pure waves we just saw is really just something going around in a circle. Take a point moving around a circle at a steady speed, and track its height. You get a perfect wave. Now chain a few spinning arrows together, from the tip to the tail, and they can draw pretty much any shape you want.

So spectrum is really a recipe of circles: how big each circle is, and where it starts. The FFT is how computers find that recipe fast enough to do it live. It runs billions of times a day, in your phone, your Wi-Fi, your music apps and even in hospital scanners. But I don't just want you to walk away from this video knowing that it's useful. I want to show you that it's elegant, because its speed itself comes from one simple fact about circles, used over and over again.

To get there, we need one tool: complex numbers. We know complex numbers as points on a plane. The real part tells you how far right, and the imaginary part tells you how far up. So three plus two i sits right here. The cool part is multiplication. Multiplying by i doesn't stretch anything. It rotates the point a quarter turn, counterclockwise. Do it again, that's another quarter turn, and you end up at minus one. That's really all "i squared equals minus one" means. In general, when we multiply two complex numbers, their lengths multiply and their angles add up. Remember this because it is important throughout the video. Now let's think about the euler formula for a second. e to the i theta equals cos theta plus i sine theta. The nuance to this equation is that it may be visualised as a location. e to the i theta is the point on the unit circle at angle theta. Going across, it's cos theta, and going up, it's sine theta.

As theta grows, the point walks around the circle. At theta equals pi, you're halfway around, sitting at minus one. At two pi, you're back where you started. And since multiplying adds angles, e to the i a times e to the i b is just e to the i, a plus b. You spin, and then you spin some more. Exponents turn into rotations. This is my favourite way to picture it. Let the point spin around the circle at a steady rate, and add time as a third direction, coming out towards you.

As it spins and time moves forward, it traces out a coil. It looks just like an old telephone cord. Look straight down the cord, and all you see is the circle. Turn it on its side, and its shadow is a cosine wave. Look at it from above, and the shadow is a sine wave. So it's really one spinning motion, and the two waves are just its shadows. A tighter coil means it's spinning faster, so at a higher frequency. And if the coil is wound the other way, it's spinning clockwise. That's e to the minus i theta. Our transform uses these clockwise coils, so keep this picture in mind. Next, let's chop the circle into equal pieces. Put N points around the unit circle, evenly spaced. If N is eight, you get eight points, each an eighth of a turn apart. These are called the roots of unity, because if you raise any of them to the power of N, you land back on one. I'm going to call one step around this circle W N. So W N is e to the minus two pi i over N.

Every other point is just a power of it. W N squared is two steps, W N cubed is three steps, and once you've gone all the way around, you're back at one. This W N is kind of the main character of the whole video. From now on, whenever you see something yellow, think: one step around the circle. One last tool, and you already know this one: polynomials. Take our samples, x0, x1, x2, and so on, and use them as the coefficients of a polynomial.

So P of z is x zero, plus x one times z, plus x two times z squared, and so on. Evaluating a polynomial at some point just means plugging a number in. This is where I'm going with all of this. The transform we're about to see is nothing more than evaluating this polynomial at those points around the circle. Keep that in the back of your head, because it's what makes the fast algorithm possible. So this is the Discrete Fourier Transform. X of k equals the sum, over n from zero to N minus one, of x of n times W N to the n k. Let's go through it piece by piece. On the left you've got X of k. That's one output, and it tells you how much of frequency k is in the signal. On the right, every single input sample x of n gets used. Each one gets multiplied by a twiddle, which is a point on the circle. Then you add everything up.

So you've got N outputs, and every one of them touches all N inputs. But what is that sum actually measuring? Let's actually try to visualise things. How we are going to do that is baically taking a signal, and wrapping it around a circle. Here's our signal: sixteen samples of a slow tone and a faster tone added together. Each sample turns into an arrow from the centre as long as the sample's value. The twiddle decides which way it points: sample n gets turned n times k steps clockwise.

So n goes up, the arrows sweep around the origin, and the signal winds up into a curve. Watch the little marker moving along the signal. Wherever it is, the matching arrow is drawing that bit of the curve. The dashed lines show every time we finish one full turn, and the number up here is the winding speed. Now, where's the balance point of all these arrow tips? It's basically their average position. For most winding speeds, the tips spread out pretty evenly around the circle,

so the balance point stays near the middle. Nothing interesting yet. Now let's sweep the winding speed and keep track of what happens. Down here, I'll plot how far the balance point is from the centre at every speed. Watch what happens when we get to speed two. Every bump of the slow tone lands on the same side, so the balance point swings out. That's a peak. Keep going, and it drops back to the middle. Then, as the fast tone lines up, we get a second peak. So we put in a pair of tones, and we got a pair of peaks. The winding picks up each frequency on its own, so a mix of tones just gives you one peak per tone, side by side. And that's how your phone pulls a chord apart. What about that big spike right at the start? That's because our signal sits above zero on average, so with no winding at all, everything leans to one side. It's only measuring that average. One last thing. X of k is the sum of the arrows, not their average,

so it's N times the balance point. That means the longer a tone lasts, the taller its peak gets. Let's do one output by hand. Four samples: one, two, three, four. With four points, one step around the circle is a quarter turn clockwise, so W four is minus i. Let's find X of one. The first sample gets multiplied by W to the zero, which is one, so that's just one. The second sample gets multiplied by minus i, so that's minus two i. The third sample gets W squared, which is minus one, so minus three. The last sample gets W cubed, which is plus i, so four i. Now add them all up. One minus three is minus two, and minus two i plus four i is two i. So X of one is minus two plus two i. That's four multiplications for one output, and we need four outputs, so sixteen multiplications.

Now put that sum right next to our polynomial from before. DFT multiplies x of n by W N to the n k. The polynomial multiplies x of n by z to the n. Those are exactly the same if z is W N to the k. So X of k is just P evaluated at W N to the k. In other words, the DFT evaluates one polynomial at all N points around the circle. That's the first big idea of this video. And it's the reason a fast algorithm can exist at all, because those points on the circle have a very special structure.

So how expensive is the direct DFT? Let's count. Let's draw a grid of all the work. Each row is one output, X of k, and each column is one input, x of n. Every cell is one multiplication: one sample times one twiddle. To get every output, you have to fill in every single cell. That's N rows times N columns, so N squared multiplications. For our four-sample example that's sixteen, which is fine. For eight samples it's sixty-four, still fine. But this grid grows with the square.

If you double the length of the signal, the work goes up four times. But real signals aren't eight samples long. One second of CD-quality audio is forty-four thousand one hundred samples. A single frame that a phone analyses is often four thousand and ninety-six samples. A medical image can have millions of pixels. At four thousand and ninety-six samples, N squared is almost seventeen million multiplications, for one frame. A tuner wants dozens of frames every second. And at a million samples, you're at trillion. The grid just gets too big to fill.

If we want Fourier transforms in real time, we need a way to skip most of those cells, and still get exactly the same answer. The way out is something you've probably seen before in the world of divide and conquer. Think about merge sort. Sorting a list the simple way takes about N squared comparisons. But if you split it in half, sort each half, and then merge the two sorted halves, which is cheap, and you keep recursively doing that the cost drops to N log N.

The FFT does the same kind of thing. You split one big DFT into two smaller ones. And since the cost grows with the square, two half-size problems only cost half as much as one full-size one. So the question is, how do you split a DFT, and how do you glue the two answers back together? So how does that work? Take a signal sampled at eight points. Instead of cutting it into a left half and a right half, deal the samples out like cards: even positions go in one pile, and odd positions go in the other. Look at the even pile by itself. It's the same wave, just sampled half as often, so four samples instead of eight. It still follows the whole signal, just on a coarser grid. Now the odd pile. Same wave again, also four samples. But every odd sample comes one step later in time than the even one next to it. So the odd pile is the even pile's grid, shifted over by one sample. On its own, neither pile can tell every frequency apart.

Together, though, they've got everything. So instead of one problem, we now have two half-size problems: the same signal, seen through two coarse grids, and one of them is slightly delayed. So what does a one-sample delay do to the frequencies? Think of each frequency as a spinning arrow. If you delay the signal by one sample, every arrow has had one sample less time to spin, so it's behind by some angle. And the faster arrows fall further behind:

frequency k is behind by k steps of one N-th of a turn. That lag is exactly W N to the k, which is a twiddle factor. So the recipe goes like this. Start with the even pile and take its transform. Then transform the odd pile, and rotate each of its frequencies by W N to the k to make up for the delay. Add the two together, and you got the full transform. So what did we gain? from all of this? The full DFT was one N by N grid, so N squared cells. Now we've got two grids,

each N over two by N over two. Each one is a quarter of the area, so together they're half. Plus a few extra multiplications, one twiddle per output, to glue them together. For big N, that barely matters. That's one trick, and the work is already cut in half. And it gets better, because each half is a DFT too, so we can do the same trick again, and again. But first, let's make all of this exact with some algebra.

now, let's make the picture we established precise. Here's the DFT again. The sum goes over every n. I'm going to split it into two sums: one over the even values of n, and one over the odd values. Nothing gets lost, because every sample still ends up in exactly one of the two sums. For the even indices I'll write n equals two r, and for the odd ones, n equals two r plus one. Our new counter, r, runs from zero up to N over two, minus one.

So X of k equals the sum of x of two r times W N to the two r k, plus the sum of x of two r plus one times W N to the two r plus one, times k. Purple is even and orange is odd, the same colours as our pile of cards. Look at the odd sum. Its twiddle is W N to the two r plus one, times k. Exponents add, so that's W N to the two r k, times W N to the k. And W N to the k doesn't depend on r at all. It's the same in every term of that sum, so I can pull it out front.

Now the two sums look almost the same. Each one is a sum over r with the twiddle W N to the two r k. The only difference is that one U uses the even samples, the other uses the odd samples, and the odd one has an extra W N to the k in front. That extra factor is the delay we saw with the cards. Now the twiddle inside the sums, W N to the two r k. That's W N squared, raised to the r k. So what is W N squared? W N is one step around the circle. Squaring it doubles the angle, so it's two steps, and

that's exactly one step on a circle with only half as many points. So W N squared is W N over two. Let me show you. These are the eight points for N equals eight. Now square every one of them, which doubles each angle. They all land on just four points, the four-point circle, and each of those gets hit exactly twice. This is the second big idea. The even and odd sums don't need the full circle. They live on a circle with half as many points, which means each of them is a DFT of half the size.

Let's give those two sums names. The even sum is E of k, the half-size DFT of the even samples. The odd sum is O of k, the half-size DFT of the odd samples. And now the whole derivation fits on one line. X of k equals E of k, plus W N to the k times O of k. If you read that out loud, it says the full transform is the even transform plus a twiddled odd transform. That's exactly the recipe we guessed from the cards, and now we've proved it. You can see the same split in the polynomial picture,

and there the reuse is even easier to spot. Take P of z, and group the even terms and the odd terms. The even terms only have even powers of z, so they make a polynomial in z squared. The odd terms, once you pull out one z, also make a polynomial in z squared. So P of z equals P even of z squared, plus z times P odd of z squared. To evaluate P at all points on the circle, you only need the two smaller polynomials at the squared points.

And the squared points are exactly the smaller circle we just saw. Half the points, and half the degree. There's one loose end remaining. of k needs k to go all the way from zero to N minus one. But E and O are half-size DFTs, so they only give us N over two outputs each. What happens once k goes past halfway? The circle saves us again. Half-size transforms live on the half-size circle, so they repeat every N over two steps. E of k plus N over two is just E of k, and the same goes for O.

So for the second half of the outputs, we reuse the exact same E and O values we already have. Only the twiddle changes. Let's check this with real numbers. Back to our four samples: one two three four. The even samples are one and three. A two-point DFT is just the sum and the difference, so that gives four and minus two. The odd samples are two and four, which gives six and minus two. Now the first output, X of zero, is E of zero plus O of zero, so four plus six, which is ten.

And that's just the sum of all the samples, like it should be. The second output, X of one, is E of one plus W four times O of one. That's minus two, plus minus i times minus two, which comes out to minus two plus two i. That's exactly what we got by doing it the long way. So here's where we are. Our formula says X of k equals E of k plus W N to the k times O of k. E and O are the half-size transforms, and we just saw that they repeat, so the second half of the outputs get them for free. That leaves only one thing doing real work: the twiddle times O. For eight points, that's eight twiddles, one for every output. But look at where those twiddles actually sit. They aren't eight random numbers. They're evenly spaced around the circle,

and that pattern is going to save us a lot of work. So let's look at the two properties of the twiddle that make it happen. Property one is periodicity. Take N steps around the circle and you're back where you started. So W N to the k plus N is just W N to the k. The twiddles just keep repeating. That's why we never need more than N different twiddles, and in practice we only ever need half of them. It's also why E and O repeat. They're built from the twiddles of the smaller circle, which come back around every N over two steps. That's exactly what let us reuse E and O for the second half of the outputs.

Property two is the one that makes the FFT fast. What happens if you go half a turn further? Half a turn by itself is minus one. So W N to the k plus N over two is W N to the k, times minus one. Watch the arrow. Add half a turn, and it points the exact opposite way. Same length, opposite direction, so it's just the negative. That means the twiddle for the second half of the outputs is just a minus of the twiddle for the first half. We don't have to compute it at all. We just flip the sign.

and we're there. Finally let's put both properties into our formula. For the first half of the outputs, X of k equals E of k plus W N to the k times O of k, just as before. For the second half, at k plus N over two, E and O repeat, and the twiddle flips its sign. So X of k plus N over two equals E of k minus W N to the k times O of k. Look at those two lines. Same E, same O, same product. So you compute the twiddle times O just once, then add it for one output and subtract it for the other.

That's the deal: one multiplication gives you two outputs. This is the core of the FFT, and it's important enough to get its own picture and its own name. Next, we take this one split and run it all the way down which will be further in detail in the next part of this video which should give you a look into the broader view of the whole FFT machine. Okay, so let's quickly remember where we stopped. The DFT basically evaluates a polynomial at N points around a circle. Then we saw that if you split the samples into even and odd, the full transform breaks into an even transform plus a twiddled odd transform. And because of the half-turn symmetry, one multiplication actually gives us two outputs. Nice right? Now, in this part, we will take that one split and push it as far as it can go. For our example, we will use 8 samples, x0 to x7.

So here is the first split, the same one from part 1. To get the 8-point DFT, we need two 4-point DFTs. One for the even samples x0, 2, 4 and 6 and one for the odd samples x1, 3, 5 and 7. But wait, a 4-point DFT is still just a DFT, so nothing's stopping us from splitting it the same way again. Take the even group: its own even positions hold x0 and x4 and its own odd positions hold x2 and x6. Do the same with the odd group and we get x1 and x5, then x3 and x7. So now we have got 4 groups of 2.

Keep an eye on the order here, because it is going to matter a lot later. Let's keep going: each group of two splits again into two groups of one. Now I have one question: what is the DFT of a single sample? With only one point, there is only one twiddle, W to the power of zero, and that is just one. So the DFT of one sample is the sample itself; there is nothing to compute here. That is our base case. The recursion stops at single points because they are already their own transforms. So the whole problem breaks into a tree: 8 at the top, then 2 fours, then 4 twos, then 8 ones. And here is the interesting part: all the actual work happens on the way back up. Here is the whole idea as code. It's pretty short. The function takes a list of samples. If the list has length 1, you just return it, since that's the base case. Otherwise, we call the same function on the even-index samples and again on the odd-index samples. That gives you E and O.

Then for each k in the first half, you compute twiddle times O of k just once. Slot k gets E plus that product, and the matching slot in the second half gets E minus it. Notice that there is no double loop over every input and every output like the direct DFT had. Each call only does one pass over its outputs and leaves the rest to the recursion. And that's the whole FFT in a dozen lines. The rest of this part is about understanding what those lines do to the data and how to run them without recursion. Now let's watch the work actually happen as we climb back. Pair up the single samples and combine each pair using our recipe, which is basically a sum and a difference. With only 2 points, the twiddle is just 1, so there is no real multiplication here. One level up, we combine pairs of 2-point results into 4-point results. Now the twiddles come from the 4-point circle, so they are 1 and minus i. At the top, we combine 4-point results into the final 8-point answer using the

8-point circle. See, every level does the same thing: take two halves, twiddle the bottom one, then add and subtract. We do this little move so many times that it has its own name. So here is the whole move on its own. Two numbers come in, and we call them a and b. First b gets multiplied by a twiddle W. Then you get two outputs: a plus Wb on the top and a minus Wb on the bottom. If you draw it, you've got two inputs on the left, two outputs on the right and lines crossing in the middle. The crossing lines look like a pair of wings, which is why it is called a butterfly. There is only one multiplication in this whole picture; everything else is just adding.

The way you read it is very simple: when lines meet at a node, they get added; a minus sign on the line means you subtract; and the twiddle sits on the line it multiplies. Let's see what a butterfly actually does on the complex plane. Here is a and here is b. Multiplying b by the twiddle just rotates it. So Wb is the same length as b, just turned around the circle. The top output, a plus Wb, is Wb stuck on its tip. The bottom output, a minus Wb, sticks on the same arrow but pointing the other way. So the two outputs are perfectly symmetric around it, like a see-saw balanced on the tip of a. As the twiddle changes, the see-saw just spins around that point. It never stretches, because the twiddle never changes length. So it's just one rotation and then a flip. That's all the butterfly ever does. Now let's count what one butterfly costs.

It's one complex multiplication for W times b, plus an addition and a subtraction. That's all. So how many butterflies does it take to merge two halves into one answer of size N? We need one butterfly per pair of outputs, so N over 2 butterflies. Compare that with the direct DFT, where every single output costs N multiplications. Here, every pair of outputs costs just one. And this is exactly where the saving comes from. The direct way pays for every output separately.

The butterfly pays once per pair and shares the product. So each level of our tree costs about N over 2 multiplications. Now the only question left is: how many levels are there? Now let's count all the work one level at a time. Here is the recursion tree for 8 samples. At the top level, we combine two halves of 4 into 8 outputs. That's 4 butterflies. One level down, there are two subproblems of size 4. Each needs two butterflies. So again, 4 butterflies. At the bottom, there are four subproblems of size 2, and each needs one butterfly. Four butterflies again. See the pattern? As we go down, the problems get smaller but there are more of them.

So every level does the exact same amount of work: N over 2 butterflies, touching all N values once. So how many levels are there? Each level cuts the problem size in half. We start at N, then N over 2, then N over 4, and keep going until we hit 1. The number of times you can halve N before reaching 1 is exactly log base 2 of N. That's basically what log 2 means. Let's plug in those numbers. For 8 samples, 3 levels: 8, 4, 2, then single points. For 1024 samples, that's 10. And for 1 million samples, it is only 20. So the tree gets wide very fast, but it stays very shallow.

That's what the logarithm is doing for us. Now let's put those two facts together. Every level costs N over 2 multiplications and there are log N levels. So the total is N over 2 times log N. In big-O notation, the FFT is order N log N. For our small example, that is just 12 multiplications, compared to 64 for the direct DFT. And you know what? It's actually even better than that, because many of the twiddles are 1 or minus i, which cost nothing. But we don't need that detail now.

N log N is the main result; remember this one. We already know about merge sort's analysis from class. So there is a second way to get the same answer, which is to write a recurrence. Let T of N be the cost of one FFT of size N. To do one, you do 2 FFTs of size N over 2 and then N units of work to combine them with butterflies. So T of N equals 2 T of N over 2 plus N. That's exactly the same recurrence as merge sort: two half-size subproblems plus linear work to merge them. So it solves in the same way, to N log N. If you know the master theorem, this is the balanced case. The work is the same on every level, so you pay it once per level and there are log N levels. It is the same tree and the same answer, just written in one line. Remember the red grid from part 1? Every cell was one multiplication and there were N by N of them. It's a square, so it grows in two directions at the same time. Now here is the FFT's work drawn in the same way.

Each level of the tree is one green row with N over 2 butterflies, one cell each, and there are only log N rows. Let's put them side by side at the same scale. For 8 samples it doesn't look like much: 64 red cells against 12 green ones. But watch what happens when N grows. The red square grows in both directions. The green strip only gets longer and barely any taller. The gap is the whole reason why the FFT exists. Let's put some real numbers on it. For 1024 samples, that's about a million multiplications for the direct way, and about 5000 with the FFT, so about 200 times less work. For a million samples, it's about a trillion versus 10 million; that is 100,000 times less. And the gap keeps getting bigger and bigger as N grows, because N log N only grows a little faster than N itself. In practice, an FFT costs about the same as reading through the data a few times. So now we know it's fast.

Let's sort out one more detail we noticed back in the tree, which is the order of the inputs. Let's go back to the bottom of the recursion tree and read the leaves from left to right: x0, x4, x2, x6, x1, x5, x3, and x7. That's a weird order. It is not sorted, but not random either. And since all the combining starts at the leaves, this is the order the inputs have to be in before the first level of butterflies. So if we want to skip the recursion and run the butterflies directly, we need a quick way to get this order. And there's a trick hiding in binary.

Write each index in binary with 3 bits, since we've got 8 samples. 0 becomes 000, 1 becomes 001, 4 becomes 100, and so on. Now reverse the bits of each index, like we're reading it from a mirror. 001 becomes 100, so 1 becomes 4. 011 becomes 110, so 3 becomes 6. Do that for every index and read the reversed values in order. You get 0, 4, 2, 6, 1, 5, 3 and 7. That's exactly the order of the leaves. That's why it is called bit-reversed order.

And it's cheap, because reversing the bits of an index only takes a few shifts, so reordering the whole input is just one pass over the data. It also pairs the indices up: if one becomes four, then four becomes one. So you can do it in place by swapping pairs. So why does flipping work? Think about what each split was looking at. The first split asked whether the index is even or odd, and that's just the last bit. The second split looked at the second-to-last bit, and so on up the index. So the recursion sorted the samples by the last bit first, then by the next bit, and so on. And sorting by the bits from right to left is the same as sorting by the reversed number. Take 6, which is 110. Its last bit is 0, so it went to the even side.

Its middle bit is 1, so it went to the odd side of that. Its first bit is 1, so odd again. Read those choices in order, 0 1 1, and you get 3, and 6 sits in position 3 in the leaves. So the recursion was reading the indices backward the whole time. Now we can draw the whole algorithm as one picture, called the butterfly diagram. The 8 inputs go in on the left in bit-reversed order and 8 outputs come out on the right in normal order. Stage 1 is all about neighbouring pairs. There are 4 butterflies and each one joins 2 values that sit next to each other. Let's zoom in on one. The twiddle factor here is W2 to the power 0, which is just 1. So each of these butterflies just outputs a sum and a difference.

These are the 2-point DFTs from the bottom of our tree, and that's why the inputs have to be bit-reversed: it puts each pair, like x0 and x4, right next to each other. Stage 2 works on groups of 4. Each butterfly now joins values that are two rows apart. Let's zoom in. The twiddles now come from the 4-point circle: W4 to the power 0, which is 1, and W4 to the power 1, which is minus i. In each group, the first butterfly uses 1 and the second one minus i. Look at the second one.

Multiplying by minus i is just a quarter turn: you swap the real and imaginary parts and flip a sign. There is no real multiplication at all. Now zoom back out. After this stage, each group of 4 holds a complete 4-point DFT. The top group is E and the bottom group is O. Stage 3 goes through the whole diagram. Each butterfly joins a value from the top half with a matching value from the bottom half, 4 rows apart. Zoom in one more time. This is exactly the formula from the first part: X of k equals E of k plus W8 to the power k times O of k. And the output 4 rows down is the same thing with a minus. So that's 4 butterflies, with 4 twiddles from the 8-point circle. And zoom out. Now watch the data flow through the whole thing: 8 values go in, they go through the 3 stages of butterflies, and 8 frequencies come out. That's 12 butterflies in total, where the direct DFT needed 64 multiplications.

There's another way to look at the same diagram. Turn every value into a node and every line into a connection, and line up the nodes in columns. What you get looks like a neural network with exactly one input layer, two hidden layers and one output layer. The connections have fixed weights: 1s, minus 1s and twiddle factors. Nothing gets learned here, because every weight is set by the circle. But the data still flows through it layer by layer, just like a forward pass in a network.

So it's the same picture, just drawn differently. And next time someone shows you a deep network, you will know that the FFT was stacking layers like this way before neural networks were popular. And the network view shows you the speed-up straight away. The direct DFT drawn as a network is just a single dense layer, with every output connected to every input. That's N squared connections, so for 8 points, 64. The FFT replaces that one dense layer with a few sparse ones. Each node only has two connections coming in: that's 2N connections per layer, times log N layers. For 8 points, you don't save much, but for 1000 points, it's a million connections against 20,000. It computes the same thing with way fewer wires.

The diagram also shows you how to write the FFT without recursion. You just walk through it from left to right. First put the inputs in bit-reversed order. Then loop over the stages. Inside each stage, loop over the groups. And inside every group, loop over its butterflies. That gives you a nested loop, three deep. The outer loop runs log N times. The two inner loops together always visit N over two butterflies. So the cost is the same N log N that you've counted before, but without any function calls or extra lists. The only thing that changes from stage to stage is the spacing. In the first stage, partners are one row apart. In the second, they are two rows apart. And in the third, four rows. Each stage doubles the spacing and halves the number of groups. There's one more trick that makes this practical, which is that it runs in place. Look at a single butterfly. It reads two values and writes two values back in the same two slots.

And once the butterfly has read its inputs, it never needs them again. So you only need one array of N numbers. Each stage overwrites it, slot by slot. So you do not need any copies or extra memory. That's why this is the classic textbook version, and it's at the core of real implementations: one array, bit-reversed once, then rewritten log N times. On a real computer that matters as much as the number of multiplications, because moving data around is much slower than the arithmetic.

So here is the iterative FFT in full. The first line that really matters copies the input in bit-reversed order. The outer loop goes over the stages. The variable called size is the length of the transform we are building: 2, then 4, then 8, doubling every time until it reaches N. The middle loop goes over the groups, which start size apart. And the innermost loop handles the butterflies inside one group, and the body is just the butterfly. t is the twiddle times the bottom value, u is the top value, and the pair of slots get u plus t and u minus t. You know that it is just the diagram. So if you can draw the diagram, you can write this code. And if you ever get lost in the indices, draw the 8-point diagram and trace one butterfly by hand. That's the best way to debug it.

Everything so far has assumed N is a power of 2. Why is that? It's because every split cuts the problem exactly in half: 8 splits into 4 and 4, then 2 and 2, then 1s. But now try 6 samples. That splits into 3 and 3. But 3 is odd. You cannot split a list of 3 into an even half and an odd half. So the radix-2 recursion gets stuck: there is nowhere left to split. So what do you do with a signal of length 6, or a 1000, or 44,100? Real recordings pretty much never come in a neat power of 2.

The simplest fix is to make it a power of 2. That's called zero padding. You take your samples and add zeros at the end until you reach the next power of two. So six becomes eight. Does that change the answer? A little, but not in a bad way. The zeros don't add anything to the sum, so you're still measuring the same signal. What changes is where you sample its spectrum. With more points, the frequencies you get are closer together. Here is a pulse of length eight and it's eight-point spectrum. If you pad it to sixteen, every second bar is exactly one of the old ones, and the rest are new ones. So zero padding doesn't add any new information. It just shows you the same spectrum on a finer grid. So what goes wrong if you ignore all of this? If you just feed 6 samples into a radix-2 FFT, it won't work, because it gets stuck after the first split. And if you cut the signal down to 4 samples to make it fit, you are throwing away real data. Padding has its own trap too.

Your frequency bins are now spaced by the sample rate over 8, not over 6. If you read a peak using the wrong spacing, you'll name the wrong frequency. And padding can't separate two tones that are really close together. Only a longer recording can do that. There are FFTs for other lengths as well, but that's a topic for another day. With power-of-2 lengths, everything we built so far works perfectly. Next, we make this concrete with a full 8-point FFT done by hand.

Okay, quick recap. The DFT evaluates a polynomial at points on a circle. Splitting the samples into even and odd turns it into two half-size problems, which get glued back together by butterflies. Keep repeating that, and you end up with a diagram that has log N stages and bit-reversed inputs. Now we're going to actually run it, by hand, on eight numbers. Our input is one, two, one, and then five zeros. So it's a small bump right at the start. Before we compute anything, let's make a guess.

The first output, X zero, is always just the sum of the inputs, so it should be four. And a smooth bump doesn't have any fast wiggles in it, so I'd expect most of the strength at low frequencies, and very little near the middle of the spectrum. Step zero is putting the inputs in bit-reversed order. Each index gets its bits flipped like a mirror. Zero stays at the top. Index four, which is one zero zero, flips to zero zero one, so it moves into row one. Index two, zero one zero, is its own mirror image, so it stays in row two. And so on down the list. So going down the left side the diagram, we've got 1, 0 1 0 2 0 0 0. It looks scrambled, but now every butterfly in the first stage has its two partners

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent