How The Fast Fourier Transform Actually Works
From the publisher’s feed, collected in the ZeroLabs newsroom.
The Algorithm Built To Catch Nuclear Tests Now Runs Your SpotifyLast month a song came on in a supermarket and I half recognized it. Not enough to name. Enough to be annoying.So I did the thing everyone does. Phone out, arm up toward the ceiling speaker, standing beside the frozen peas looking like a man photographing air. Four seconds later my phone gave me the artist, the album, and the year it came out.Then it told me the song was from 2004, which I did not need to know about myself that day.Here is the part that took me embarrassingly long to work out. My phone did not listen to that song. Not in any sense you would call listening. It took the noise in that supermarket, turned it into a picture, deleted about 99% of the picture, and matched the leftovers against a fingerprint database.The thing that turns sound into a picture is called the Fourier transform. A French bureaucrat invented it in 1807 while trying to understand how heat crawls through metal. It is now inside your phone, your car stereo, every photo on your camera roll, the machine that would scan your brain if you needed one, and the courtroom evidence that proves a recording was not tampered with.The face of a man running 200 year old French mathematics without knowing it. Standing next to peas.I am going to build this up from absolutely nothing. If the word “frequency” makes you tense, you are exactly who I wrote this for. By the end you will have written a working spectrum analyzer and you will know what all the confusing bits mean.First, what sound actually isPut your hand flat on a speaker while music plays. You feel it push.That is the whole story. A speaker cone shoves air away from itself, then pulls back, then shoves again. Those pushes travel outward as tiny pressure bumps. When they reach you, they wobble your eardrum, and your brain turns that wobbling into music, or a doorbell, or your name.A microphone is that in reverse. A thin membrane sits there getting shoved by the same air, and a chip measures how far it moved. Thousands of times a second. Each measurement is one number.So a “signal” is nothing fancy. It is a list of numbers, measured in order, over time. That is it, and I promise it stays that simple.Now, frequency. Frequency means how many times something repeats per second, measured in hertz. A guitar string vibrating 440 times a second is 440 Hz, which musicians call A. Double it to 880 Hz and it is the same note, one octave up. Halve it to 220 Hz and it is the same note, lower.Low frequency, deep. High frequency, sharp. Nothing more.And here is the odd bit. Your ear does not receive one lump of sound and then puzzle it out. Inside your inner ear is a coiled tube called the cochlea, and along that tube sit tiny hairs. The ones near the entrance react to high notes. The ones deeper in react to low notes.Your ear is physically laid out by frequency. It is a mechanical sorting machine made of jelly and hair, and it has been running since before you were born.Evolution shipped this before we invented the number zero. The FFT is a software port of your inner ear.Which is why you can pick your friend’s voice out of a loud room. Your ear has already separated the ingredients before your brain gets involved.A quick test you can failSomewhere around 17,000 Hz there is a sound most people under twenty can hear and most people over thirty cannot. High frequency hearing goes first as you age. Nothing dramatic, it just quietly leaves.In the mid 2000s a British inventor sold a device based on this called the Mosquito. Shopkeepers mounted it outside and it emitted a piercing 17 kHz whine. Loitering teenagers found it unbearable. Adult customers walked past hearing absolutely nothing.Then teenagers started using the same tone as a text message ringtone so they could get messages in class without the teacher hearing. Which is, I think, the correct response.A weapon repurposed into a ringtone in roughly one school year. Frequency is a loophole.Two things fall out of this that we need later. Human hearing tops out around 20,000 Hz. And “how loud is it right now” and “which frequencies are in it” are genuinely different questions with genuinely different answers.The two shelvesTwo people describe the same three second clip.One says the sound got loud, then quiet, then there was a thud. That is a description over time.The other says there is a low note, a mid note, and a faint hiss. That is a description over frequency.Neither has more information. Same clip, filed on a different shelf. And you can move between the shelves perfectly, in both directions, forever, without losing a thing.Left is honest and unreadable. Right is readable and equally honest. Every single thing in this article happens between those two boxes.The word “domain” just means “which shelf”. Time domain, frequency domain. That is all the word is doing, and I resent how long it took someone to tell me.Moving left to right is the Fourier transform. Right to left is the inverse. Two directions, one machine.Why bother? Because some problems are miserable on one shelf and trivial on the other. My upstairs neighbor plays music and I only ever hear the bass, because the ceiling passes low frequencies and eats the high ones. Try describing that filtering in terms of a wiggly line. Now try describing it as “keeps everything under 200 Hz”. One of those sentences is short.The picture I want stuck in your headEveryone online explains this with a smoothie, where you unblend a drink back into fruit. It is a fine analogy. I am using a different one, because mine keeps working when things get technical.A jar of loose change. Yours is in a drawer with dead batteries and a takeaway menu from a place that closed in 2019.Somebody asks how much is in there. You say about forty seven dollars. True. Also useless, because you cannot spend a heap.Pour it into a coin sorting machine. It rattles, and out come labelled trays. Twelve quarters, thirty dimes, eight nickels, two hundred pennies.Same money in, same money out, suddenly spendable. Hold on to the pennies, they turn into a 90% discount later.The jar is your signal. The machine is the transform. The trays are the spectrum. And you can tip the trays back in and get exactly the jar you started with, coin for coin.That last point has a name, Parseval’s theorem, and it is the reason engineers trust this thing enough to put it inside pacemakers. Nothing is invented on the way through. Nothing is quietly lost.Hold on to one more thing about the trays. Once your money is sorted, you can throw away all the pennies and the jar gets dramatically lighter while staying worth roughly the same. Remember that. It is a ninety percent discount on the entire internet and we will come back to it.The three knobsEvery ingredient in that jar is a sine wave. One pure tone, one smooth repeating curve, and it has exactly three settings.Amplitude is height. Taller bump, louder sound. Frequency is speed. Bumps per second. Phase is how late it started.Three knobs, and that is the entire vocabulary of the field. Beginners turn two of them and wonder why the audio sounds broken.Beginners skip phase. Beginners then rebuild their audio and it sounds like a filing cabinet falling downstairs.Phase matters more than it looks. It is how you know where a sound came from. A car horn on your left reaches your left ear a fraction earlier than your right. Your brain reads that gap between two ears and points. It is doing phase comparison in real time, at traffic, while you think about dinner.Now stack three of these boring curves on top of each other.Adding is easy. Un-adding is the hard part, and it is the only reason this whole field employs anyone.Look at the right hand line, then try to guess the left column from it. You cannot. Nobody can. That gap between what a signal looks like and what is inside it is the entire reason this field exists.The claim that got a genius rejectedJoseph Fourier had a strange life even by French revolutionary standards. He was nearly guillotined, went to Egypt with Napoleon, ran a province as a governor, and somewhere in the middle of all that wrote the first serious argument that the atmosphere keeps this planet warmer than raw physics says it should be.In 1807 he submitted a paper about heat moving through solid objects. Inside it was a claim that sounded ridiculous.Any shape can be built from sine waves. Any shape. Including shapes with sharp corners.Round things adding up to a hard corner. Look closely at panel four, because those little horns at the edges never go away, no matter how many terms you throw at them.Lagrange and Laplace, two of the largest names alive, read it and said no. Round things do not add up to corners. The paper was refused.They were wrong, and it took four years to prove it. In 1811 the same institute set a prize on the topic, Fourier submitted again, and the judging panel, which still included Lagrange, gave him the prize. The book itself did not appear until 1822.Those small horns at the corners have a name, the Gibbs phenomenon. Add a million terms and they get thinner while staying exactly as tall, permanently overshooting by about nine percent. It is why a badly compressed image sometimes has a faint ghost halo hugging a sharp edge. Lagrange was wrong, but he was not being stupid.Rejected in 1807, prize-winning by 1811, published in 1822, running your phone by 2026. Slow start.He died in a very ordinary way. He took a fall on a staircase in May 1830 and never really recovered. My grandmother did the same thing at 81 and mostly complained about the bruise.Peer review, 1807 edition. Two of the greatest mathematicians alive, confidently wrong, in extremely good hats.Right, so how does the sorting machine workThis is the bit people expect to be hard. It is not.You have a mystery signal. You want to know whether it contains 5 Hz. So you make your own clean 5 Hz sine wave, multiply the two together point by point, and add every result into a single running total.If the signal really does contain 5 Hz, the peaks of both waves line up. Positive times positive gives a big positive. Trough times trough also gives a big positive, because two negatives multiply into a positive. The total climbs.If it does not, the peaks of one land on the troughs of the other about half the time. Positives and negatives cancel. The total collapses to nearly nothing.The whole method in one picture. Multiply, add up, write down the score. If the shaded area sits above the line, that frequency is in there.Multiply. Add up. Write down the score. Next frequency. Repeat.That list of scores is the spectrum. There is no deeper secret hiding in a later chapter, and if the notation ever stops making sense, this paragraph is where you come back to.There is a second way to picture it that I find genuinely beautiful. Instead of multiplying, wrap your signal around a central dot like wool onto a spool. Wind slowly, get one shape. Wind faster, get another. Then find the balance point of that drawing, the spot where it would sit still on a pin.For most winding speeds the balance point sits near the middle, because the drawing is evenly spread. At one specific speed the whole thing goes lopsided and the balance point lurches off to one side.Wind the signal round a dot at every speed and watch for the one that makes it lopsided. The orange dot running away is your answer.That winding speed is the hidden frequency. How far the balance point moved is the amplitude. Which direction it moved is the phase. Two numbers, one drawing, no equations yet.The equation, defusedDiscrete Fourier Transform (DFT)Breathe. It says exactly what we just did.Four colours, four ideas, zero calculus. Read the black strip at the bottom and the symbols above it stop being scary.Xk is the answer for one frequency. Bin number k. It is a pair of numbers, not one. Size means loudness, angle means timing.Σ means add everything up. It is a for-loop with a running total. Genuinely, that is the whole symbol.xn is your data. Sample number n. What the microphone actually wrote down at that instant.e−i2πkn/N is the test wave, and it is the only alien-looking part, so let me be honest about it.That expression is a spinning arrow. Euler found that this exact form produces `cos(angle) + i·sin(angle)`, which packs a cosine and a sine into one symbol.Why bother? Because a cosine on its own would miss any frequency that happens to be perfectly out of step with it. You would test for a 5 Hz tone, get a score of zero, and confidently announce there is no 5 Hz tone while it sits there in your data laughing. Carrying both a cosine and a sine makes the test immune to timing.The `i` is not mystical. It is a bookkeeping mark that keeps the cosine column and the sine column from being accidentally added together.Say the whole line out loud in English. For each frequency k, multiply every sample by a spinning arrow going at that speed, then add the whole pile up.That is the equation. It never was anything else.Now write it yourselfLet us build a signal where we already know the answer, so we can catch the code lying.import numpy as np#sample_rate = 1000duration = 1.0N = int(sample_rate * duration)n = np.arange(N)t = n / sample_rate#signal = (1.00 * np.sin(2*np.pi*2*t) + 0.60 * np.sin(2*np.pi*5*t + 1.0) + 0.35 * np.sin(2*np.pi*9*t + 2.0))Every piece, as promised.`import numpy as np` loads NumPy, the library that handles long lists of numbers quickly. `as np` is a nickname so we type two letters.`sample_rate = 1000` means we take 1000 measurements every second. This one number decides almost everything later.`duration = 1.0` is one second of recording.`N = int(sample_rate * duration)` multiplies them for the total sample count, 1000. `int()` forces a whole number, because half a measurement does not exist.`n = np.arange(N)` builds `[0, 1, 2, … 999]`. These are positions in the queue, not seconds.`t = n / sample_rate` converts positions to seconds. Sample 500 divided by 1000 is 0.5 seconds. NumPy divides the entire list in one go, which is the point of NumPy.The last block makes three sine waves and adds them. `np.pi` is 3.14159. `2np.pi` is one full lap of a circle, so `2np.pi2t` completes two laps per second. The numbers out front, `1.00`, `0.60` and `0.35`, are amplitudes. The `+ 1.0` and `+ 2.0` inside are phase offsets in radians, shifting where each wave was when the clock started.Now the transform itself. Nine lines.def slow_dft(x): N = len(x) X = np.zeros(N, dtype=complex) for k in range(N): total = 0.0 + 0.0j for n in range(N): angle = -2.0 * np.pi * k * n / N total += x[n] * (np.cos(angle) + 1j*np.sin(angle)) X[k] = total return X`def slow_dft(x)` defines a reusable recipe called `slow_dft` that takes one input, `x`, our list of samples.`N = len(x)` counts how many samples arrived. `len()` is Python’s built-in length counter.`X = np.zeros(N, dtype=complex)` makes an empty answer list of N slots, all zero. `dtype=complex` tells NumPy each slot holds a two part number, because every output carries loudness and timing. Skip this argument and Python silently throws your phase in the bin.`for k in range(N)` is the outer loop. `range(N)` gives `0, 1, 2, … N-1`. Each `k` is one frequency being tested.`total = 0.0 + 0.0j` resets the running sum. The `j` is Python’s imaginary marker. Python uses `j` instead of `i` because electrical engineers had already claimed `i` for electric current and got there first.`for n in range(N)` is the inner loop, walking every sample.`angle = -2.0 np.pi k * n / N` works out how far the test arrow has spun by sample n. The minus sign sets spin direction, and flipping it flips the sign of every phase you get back.`total += x[n] (np.cos(angle) + 1jnp.sin(angle))` is the actual work. `x[n]` grabs one sample. The bracket builds the spinning arrow the long way round so you can see there is no magic hiding in `e`. `+=` means add this to the running total.`X[k] = total` stores the score. `return X` hands back the finished spectrum.Check it against the professionals.mine = slow_dft(signal[:256])theirs = np.fft.fft(signal[:256])print(np.allclose(mine, theirs))`signal[:256]` takes the first 256 samples, because our nested loops are slow and I am impatient. `np.allclose` checks two arrays agree within a tiny tolerance, which is how you compare decimals without heartbreak. Exact equality on floating point numbers is a trap that has ruined many afternoons.It prints `True`.Your nine lines, doing the same multiplication a million times, never once asking why.Reading the output without embarrassing yourselfRun an FFT, get back a list. Index 0, index 1, index 2. Those are bins, not hertz.A bin is a slot. Each slot covers a small band of frequencies, and the FFT tells you how much energy landed in each slot. To convert a slot number into hertz you need two facts, your sample rate and how many samples you fed in.bin k sits at k × (sample rate ÷ N) hertzThe single most common source of "why does my FFT look wrong". Bins are not hertz, and everything past the orange line is a mirror.Three rules fall straight out of that.Resolution is sample rate divided by N. Our example used 1000 samples per second and 1000 samples, so each bin is exactly 1 Hz wide. A 5.4 Hz tone has no slot of its own and gets smeared across its neighbours.Half the output is a mirror. For ordinary real-world input, everything above the halfway point is a reflection of everything below it. Zero new information. NumPy’s `rfft` hands you just the useful half.For finer detail, record longer, not faster. Doubling your sample rate does nothing for resolution. Doubling your recording length halves the bin width. This one has cost me an entire afternoon and I was not even the first person in the room to suggest the wrong fix.Pull our three tones back out.X = np.fft.rfft(signal)freqs = np.fft.rfftfreq(N, d=1/sample_rate)mag = np.abs(X) * 2 / Ntop = np.argsort(mag)[-3:][::-1]print(freqs[top])print(mag[top].round(2))`np.fft.rfft` runs the real-input FFT and returns only the half worth having.`np.fft.rfftfreq(N, d=1/sample_rate)` builds the matching frequency labels for you. `d` is the gap in seconds between samples. This function exists so you do not hand-calculate bin conversions at midnight and get them wrong.`np.abs(X)` takes the size of each two part number, keeping loudness and dropping phase.`* 2 / N` is the scaling fix. Divide by N because the running sum grew with sample count. Multiply by 2 because we dropped the mirrored half and its energy went with it.`np.argsort(mag)` returns the positions that would sort the array smallest to largest. `[-3:]` grabs the biggest three. `[::-1]` reverses them so the loudest comes first.Output.[2. 5. 9.][1. 0.6 0.35]Exactly the ingredients we baked in, amplitudes included. The machine found the recipe.The bug that looks like physicsSample too slowly and reality lies to you with a completely straight face.Same wave in both rows. Only the dot spacing changed. The bottom row is a 9 Hz signal confidently pretending to be a 1 Hz one.You have seen this a hundred times without knowing. Car wheels rolling backwards in adverts. Aircraft propellers hanging in the air like they forgot to spin. Your camera samples 24 or 30 times a second, the blade goes faster than that, and the footage invents a slower motion that never happened.The rule is Nyquist’s. Sample at more than twice the highest frequency present, or filter that frequency out before you sample. There is no third option and no fixing it afterwards.That is where 44,100 comes from. Human hearing tops out near 20 kHz. Double it, add a little headroom so the anti-aliasing filter has somewhere to work, and you land at the CD standard.Nothing is wrong with the helicopter. The camera is under-sampling and the sensor is making things up.Watch it break on purpose.fast_tone = 900rate = 1000t2 = np.arange(0, 1, 1/rate)x2 = np.sin(2*np.pi*fast_tone*t2)X2 = np.fft.rfft(x2)f2 = np.fft.rfftfreq(len(t2), d=1/rate)print(f2[np.argmax(np.abs(X2))])`np.arange(0, 1, 1/rate)` builds time values from 0 up to 1, stepping by one sample period. `np.argmax` finds the position of the biggest value, so this prints the frequency of the loudest bin.We put in 900 Hz. It prints `100.0`.The 900 Hz tone folded around the 500 Hz Nyquist limit and came out the other side as 100 Hz wearing a false moustache. Your code will not warn you. Your plot will look perfectly reasonable. This is the single most expensive beginner mistake in the field, and it is expensive precisely because nothing appears to be wrong.The gotcha nobody puts in the tutorialThe FFT assumes your clip loops forever. It quietly tapes the end of your recording onto the beginning.If those two ends do not line up, you have manufactured a cliff that was never in your data. A cliff is a sharp edge. And a sharp edge, as Fourier proved to two extremely annoyed reviewers, needs an enormous pile of frequencies to describe.One tone, three outcomes. The middle panel is what your plot actually looks like, and the right panel is one line of code away.Your one clean tone smears across a dozen bins and you spend an afternoon hunting a bug in your sensor. I have done this. The sensor was fine. My cut was bad.window = np.hanning(N)X_windowed = np.fft.rfft(signal * window)`np.hanning(N)` builds a smooth bell shaped list, zero at both edges and one in the middle. Multiplying your signal by it fades both ends to silence so the seam matches perfectly. The peak gets slightly wider, which is the price, and it is a bargain.Every audio editor, vibration analyser and radio receiver on earth does this by default. No tutorial mentions it. That is the tutorial gap in one sentence.Why it is called fastLook back at those nested loops. Outer loop N times, inner loop N times. N × N operations.For a million samples that is a trillion multiplications. Days of work.Same answer, wildly different bill. The orange bar is the honest version, the tiny white sliver is the version everybody actually uses.The FFT spots that most of that work is the same multiplication computed again and again. So it splits the samples into evens and odds, solves both halves, shares the answers, and glues them together. Then does the same to each half. And again.A million samples drops from about a trillion operations to about twenty million. Roughly fifty thousand times less work. Weeks turn into seconds.import timex = np.random.randn(2048)t0 = time.perf_counter()slow_dft(x)t1 = time.perf_counter()np.fft.fft(x)t2 = time.perf_counter()print("naive", round(t1-t0, 3), "s")print("fft ", round(t2-t1, 6), "s")`np.random.randn(2048)` makes 2048 random numbers standing in for real data. `time.perf_counter()` is Python’s highest resolution stopwatch, which matters when one of your two numbers is going to be very small indeed.On my laptop, fan clearly unhappy about it, the naive version took about 4 seconds and the FFT took about 0.00004 seconds.Now the history, which is better than the maths.The 1965 version exists because of nuclear weapons. Richard Garwin at IBM wanted to verify a test ban treaty by burying seismometers in countries ringing the Soviet Union. Analysing that much ground vibration was impossible at the computing speeds of the day. He pushed two people, James Cooley and John Tukey, to find a faster transform. They did, and it went on to underpin most of digital signal processing.Then, years after 1965, somebody went digging through Carl Friedrich Gauss’s unpublished notes and found the same algorithm. From 1805. Written in Latin. Used for working out asteroid orbits. He never got round to publishing it.The most consequential drawer in applied mathematics. He had it in 1805 and filed it under later.In the year 2000, a panel put together a list of the ten algorithms with the greatest influence on science and engineering in the twentieth century. The FFT is on it, sitting next to quicksort and Monte Carlo.Six numbers from six different industries, all running the same 200 year old idea. Not one of them is a rounding of another.Real sound refuses to sit stillOne FFT of an entire song tells you which notes appear somewhere in it. Which is nearly useless. You want to know when.So chop the recording into short overlapping slices, window each one, run an FFT per slice, and stand the results up side by side.Four steps from a wiggly line to a picture of sound. Time runs across, pitch runs up, brightness is loudness.from scipy.signal import spectrogramf, tt, Sxx = spectrogram(audio, fs=44100, nperseg=1024, noverlap=512, window='hann')`fs=44100` is the sample rate. `nperseg=1024` is how many samples go into each slice. `noverlap=512` slides each slice forward by half a window instead of a whole one, so nothing important gets chopped in half at a boundary. `window=’hann’` applies the taper from earlier.It returns `f`, the frequency labels, `tt`, the time labels, and `Sxx`, a 2D grid of power values. Plot that grid with `plt.pcolormesh(tt, f, 10*np.log10(Sxx))` and you are looking at a picture of sound.A real spectrogram of birdsong. Every swoop is a note climbing, and you can read it without knowing a single note name.There is a catch, and it is not a software problem.Sharp timing or sharp pitch, pick one. This is arithmetic, not a settings menu, and every audio engineer has an opinion about it.Short window, sharp timing, blurry pitch. Long window, sharp pitch, blurry timing. You cannot have both, because measuring a frequency means watching several full cycles go by, and watching takes time. Physicists hit the identical wall in quantum mechanics and gave it a much more dramatic name.Most tools default to 1024 or 2048 samples, which is the polite middle of an argument that will never end.The move that pays salariesMains electricity leaks a faint 50 Hz hum into sensitive recordings. On a heart trace it sits right on top of the signal, and scrubbing it out of the wiggly line by hand is guesswork with a fancy job title.On the frequency shelf it is one absurdly tall bar sitting somewhere no human heart has ever been.Transform, zero one bin, transform back. Three lines of Python and a noise problem stops existing.X = np.fft.rfft(noisy)freqs = np.fft.rfftfreq(len(noisy), d=1/sample_rate)X[(freqs > 48) & (freqs clean = np.fft.irfft(X, n=len(noisy))Line three is where it happens. `(freqs > 48)` produces a list of True and False, one per bin. `(freqs `np.fft.irfft` runs the inverse and hands back a normal waveform. `n=len(noisy)` tells it the original length, because otherwise it guesses, and it guesses wrong on odd-length input.Four lines. Hum gone. In the US you target 60 Hz instead, same trick.And now the same hum, used to catch people lyingI said we would come back to that buzz. Here is where it gets good.The frequency of a national power grid is never exactly 50 Hz. It drifts constantly, nudged up and down all day as demand rises and falls. 50.02, then 49.98, then 50.01. Tiny wobbles, never repeating.Grid operators record that wobble continuously. Which means every single minute in recent history has its own unique little squiggle, logged and stored.And every microphone recording indoors quietly picks up that same hum.The most boring sound in the room turns out to be a signed and dated receipt. Cut ten seconds out and the curve stops matching.So you take a disputed audio file, run an FFT, isolate the hum, and extract its wobble. Then you slide that wobble along the national log until it locks into place. When it matches, you have the date, the time, and often the region.Cut ten seconds out of the middle and the hum develops a jump that does not exist anywhere in the recorded history of that grid. The edit lights up.The technique is called Electrical Network Frequency analysis. In the United Kingdom it has been used to authenticate recordings for years, and the matching process is largely automated.Somebody records something in a kitchen. The fridge hums. Two years later the fridge is the only witness who cannot be discredited.I find that genuinely wonderful, and slightly alarming, in about equal measure.The ninety percent discountRemember the pennies.Ninety percent of the file, gone, and nobody complains. That is not compression magic, it is just knowing which coins to bin.JPEG chops your photo into 8 by 8 pixel blocks, transforms each block with a close cousin of the Fourier transform, and then coarsens the fine detail your eye was never going to register. About 92% smaller for a good quality photo.MP3 goes harder. It models what human hearing actually notices, works out which quiet frequencies are being completely drowned out by louder neighbours, and deletes those outright. Around 90% smaller, and on ordinary headphones most people cannot tell.There is a lovely story attached to that. In the late eighties a German engineering team was tuning the compression algorithm that became MP3. One of them heard a warm a cappella vocal track playing down the corridor and realised immediately that a bare human voice with nothing to hide behind would be brutally hard to compress. So they used it as a test track and ran it through the system over and over, tweaking, listening, tweaking again.The singer had no idea for years. Someone eventually asked her how it felt to be the mother of the MP3 and she had to ask what they were talking about.The same thirty seconds, several thousand times, until the maths stopped mangling a human voice.The one that is not about sound at allIn 1952 a photograph was taken at King’s College London that changed biology forever.It does not look like DNA. It looks like a blurry X made of smudges, and if you did not know better you would assume the camera was broken.That is because it is not a picture of DNA. It is a picture of DNA’s frequencies.Fire X-rays at a crystal and they scatter off the repeating structure inside. What lands on the film is not the object, it is the diffraction pattern, and the relationship between that pattern and the actual molecule is a Fourier transform. The X shape in that photograph is what a helix looks like on the frequency shelf.The most famous image in biology is not a photograph. It is a frequency plot, and the X is what a helix looks like on the other shelf.Every protein structure in every biology textbook came out of that same move. You cannot photograph a molecule. So you record its frequency pattern and transform your way back to the shape.Same machine. Different coins.Where else it is hidingEight places it is already running while you read this. Only the coins change, the sorting machine is identical every time.A few worth knowing about.Shazam deserves its own paragraph, because it started long before smartphones. In 2002 it launched in the UK as a phone number. You dialled 2580, held your handset toward the music for fifteen seconds, the call hung up, and a text arrived with the song title. It cost 50 pence.Underneath, it builds a spectrogram, throws away everything except the loudest peaks, and turns that sparse scatter of dots into fingerprints made from pairs of peaks and the time gap between them. Shouting strangers and terrible speakers add noise between the peaks, which Shazam already deleted. That is why it works in a supermarket.MRI scanners never measure your body directly. They collect frequency information, and the image the radiologist looks at is the inverse transform of that data.Your router splits data across hundreds of narrow frequency lanes at once. The receiver runs an FFT to unpack them all in parallel, roughly fifteen thousand times a second while you scroll.Factories watch vibration. A worn bearing rings at its own pitch long before it fails, so you monitor that one bin and order the part before anything expensive stops.The gotcha list, learned the expensive waySYMPTOM LIKELY CAUSE WHAT TO DO --------------------------- --------------------- -------------------------- Peak smeared across bins Clip cut mid-cycle Apply np.hanning(N) Spectrum looks mirrored Real-valued input Use rfft, drop the top half Frequency is plain wrong Sample rate too low Check Nyquist, filter first Peak sits between bins Resolution too coarse Record longer, not faster Amplitudes look tiny Missing scaling Multiply by 2/N Phase looks like noise Reading quiet bins Only trust phase on peaks Output has no phase Forgot dtype=complex Set it on your answer array Runs forever on big data You wrote the naive Use np.fft.fftPrint it. Tape it somewhere. That table is about two years of my mistakes in eight rows.Do this tonightRecord ten seconds of yourself whistling on your laptop. Load it with `scipy.io.wavfile.read`, run an FFT, find the biggest peak. That number is your whistle, in hertz.Then run a spectrogram on the same file and watch the bright line move as your pitch moves.Then whistle one steady note, look up which bin it landed in, and set that bin to zero. Play the result back and listen to yourself get surgically removed from your own recording.That last one took me twenty minutes the first time and I still think about it.The only sentence you have to keepForget the equation. Forget the notation.Some problems are impossible on one shelf and trivial on the other, and the Fourier transform is how you move between the two without losing anything.Everything else is bins, windows, and remembering that half your output is a mirror.I still go to that supermarket. The song still gets stuck in my head. But now when I hold my phone up next to the frozen peas, I know it is not listening at all. It is sorting coins, in a jar it has never seen, in about four seconds, using a method a French bureaucrat scribbled down in 1807 while thinking about hot metal.Nobody in that aisle has any idea. Including, until recently, me.Same aisle, same song, considerably more smugness.How The Fast Fourier Transform Actually Works was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.