FFT in Python with numpy.fft
Find the frequencies hidden in a signal with np.fft.rfft, label them with rfftfreq and scale the amplitudes correctly.
- np.fft.rfft for real signals
- Frequency labels with rfftfreq
- Scaling magnitudes to amplitudes and finding peaks
50 Hzamplitude 1.00120 Hzamplitude 0.50From time to frequency
The problem
A recorded sound, a vibration or a sensor reading is a jumble of waves added together. The Fourier transform separates them, so you can see which frequencies are there and how strong each one is.
Think of it like this
The FFT is like a prism for sound. White light goes in and comes out split into its colours; a signal goes in and comes out split into its frequencies, each with its own strength.
signal💡 White light: all the waves mixed togethernp.fft.rfft(signal)🌈 The prism splits it upnp.fft.rfftfreq(n, d)🏷️ The colour of each bandnp.abs(spectrum) * 2 / n🔆 How bright each band isThe Fast Fourier Transform computes the frequency content of a sampled signal. np.fft.rfft handles real signals and returns values for frequencies from 0 up to half the sampling rate.
Key points
rfftof 1000 samples returns 501 complex values, one per frequency.np.fft.rfftfreq(n, d=1 / rate)gives the frequency in Hz of each value.np.abs(spectrum) * 2 / nturns magnitudes into wave amplitudes: 1.00 and 0.50.- The frequency resolution is
rate / n, here 1.0 Hz.
When should you use it?
- Finding the pitch of a sound or the hum in a recording.
- Vibration analysis in engineering.
- Filtering noise from sensor data.
When not to use it
- Frequencies that change over time: use a spectrogram (
scipy.signal.spectrogram). - Very short signals: the frequency resolution rate / n is too coarse.
Example code
import numpy as np
# One second of signal sampled 1000 times: 50 Hz plus a weaker 120 Hz wave
rate = 1000
t = np.arange(rate) / rate
signal = np.sin(2 * np.pi * 50 * t) + 0.5 * np.sin(2 * np.pi * 120 * t)
# rfft: the spectrum of a real signal (positive frequencies only)
spectrum = np.fft.rfft(signal)
freqs = np.fft.rfftfreq(signal.size, d=1 / rate)
amplitude = np.abs(spectrum) * 2 / signal.size # scale to the wave's amplitude
print("Number of frequency bins:", freqs.size)
print("Frequency resolution:", float(freqs[1]), "Hz")
# The two largest peaks are the two waves
peaks = np.argsort(amplitude)[-2:][::-1]
for i in peaks:
print(f"{freqs[i]:.0f} Hz amplitude {amplitude[i]:.2f}")
Result of running the code
Number of frequency bins: 501
Frequency resolution: 1.0 Hz
50 Hz amplitude 1.00
120 Hz amplitude 0.50
Code explanation
signal adds a 50 Hz sine wave and a 120 Hz wave of half the size, sampled 1000 times over one second. np.fft.rfft returns 501 complex values, one per frequency from 0 to 500 Hz, and rfftfreq with d=1 / rate labels them, 1.0 Hz apart. np.abs(spectrum) * 2 / signal.size scales the magnitudes back to the waves' amplitudes. argsort finds the two biggest peaks, which are 50 Hz with amplitude 1.00 and 120 Hz with 0.50.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Change the function or the data and predict the result before running.
- Compare the numerical answer with the exact one from SymPy or a hand calculation.
- Plot the result with Matplotlib to see what the numbers mean.
Common mistakes
Plotting the complex result
rfft returns complex numbers; take the absolute value first.
peak = np.argmax(spectrum)
peak = np.argmax(np.abs(spectrum))
Forgetting the sample spacing
Without d, rfftfreq returns cycles per sample, not Hz.
freqs = np.fft.rfftfreq(signal.size)
freqs = np.fft.rfftfreq(signal.size, d=1 / rate)
Finished this lesson?
Mark it as learned to track your progress.
Tools for this lesson
- Graph Plotter Online: Plot Points and FunctionsPlot points, a pasted table or functions like sin(x) online and download the graph as a PNG. Free graph maker that also gives you the Python Matplotlib code.
- How to Plot a Graph in Python Online (Matplotlib Examples)Plot a graph in Python online with Matplotlib: lines, functions like sin(x), data from a CSV, bar and pie charts. Run each example in your browser.
- NumPy Online: Run NumPy Code in Your BrowserA NumPy playground with no install: arrays, statistics, linear algebra, random numbers and broadcasting. NumPy 2, pandas and SciPy ready to import.