typestar

Fourier transforms in Python

rfft for real signals, fftfreq for the axis that makes it readable.

import numpy as np
from scipy import fft

rate = 500
t = np.arange(0, 2, 1 / rate)
signal_wave = 2 * np.sin(2 * np.pi * 7 * t) + np.sin(2 * np.pi * 40 * t)

spectrum = fft.rfft(signal_wave)
freqs = fft.rfftfreq(t.size, d=1 / rate)
power = np.abs(spectrum)

top = np.argsort(power)[::-1][:2]
print(sorted(freqs[top].round(1)))
print(round(float(power.max()), 1), spectrum.dtype)
print(np.allclose(fft.irfft(spectrum, n=t.size), signal_wave))

How it works

  1. rfft returns half the spectrum, which is all a real signal has.
  2. rfftfreq needs the sample spacing to label the bins.
  3. The peak bin is the dominant frequency.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
440
Tokens
165
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 90 seconds.

Type this snippet

Step 3 of 3 in Linear algebra & signals, step 18 of 23 in Scientific computing with SciPy.

← Previous Next →