Math and Science with Python

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.

  • Intermediate
  • 3 min read
  • 1 runnable example
What you'll learn
  • np.fft.rfft for real signals
  • Frequency labels with rfftfreq
  • Scaling magnitudes to amplitudes and finding peaks
Peaks in the spectrum
50 Hzamplitude 1.00
120 Hzamplitude 0.50

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

From a prism to code
signal💡 White light: all the waves mixed together
np.fft.rfft(signal)🌈 The prism splits it up
np.fft.rfftfreq(n, d)🏷️ The colour of each band
np.abs(spectrum) * 2 / n🔆 How bright each band is
A mixed signal split into its frequencies.
In one sentence

The 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

  1. rfft of 1000 samples returns 501 complex values, one per frequency.
  2. np.fft.rfftfreq(n, d=1 / rate) gives the frequency in Hz of each value.
  3. np.abs(spectrum) * 2 / n turns magnitudes into wave amplitudes: 1.00 and 0.50.
  4. 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

Open in editor →
main.py
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}")
Get a Run button for this example

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.

  1. Change the function or the data and predict the result before running.
  2. Compare the numerical answer with the exact one from SymPy or a hand calculation.
  3. Plot the result with Matplotlib to see what the numbers mean.
Run in the Python compiler →

Common mistakes

Plotting the complex result

rfft returns complex numbers; take the absolute value first.

Problem
peak = np.argmax(spectrum)
Fix
peak = np.argmax(np.abs(spectrum))

Forgetting the sample spacing

Without d, rfftfreq returns cycles per sample, not Hz.

Problem
freqs = np.fft.rfftfreq(signal.size)
Fix
freqs = np.fft.rfftfreq(signal.size, d=1 / rate)

Finished this lesson?

Mark it as learned to track your progress.

Tools for this lesson