TExcelTAD
Home › SciPy › SciPy Fourier Transforms

SciPy Fourier Transforms

Any signal can be described as a sum of sine waves of different frequencies. The Fourier transform finds those frequencies and their strengths. It moves a signal from the time domain (value at each moment) into the frequency domain (amount of each frequency). The fast algorithm for computing it, the FFT, is one of the most important algorithms ever written. SciPy's implementation lives in scipy.fft.

A first FFT

Let's build a signal from two known tones — 5 Hz and 12 Hz — and see whether the FFT finds them. For real-valued signals use rfft (it skips the redundant negative frequencies) and rfftfreq to get the frequency of each output bin:

python · try it yourself
import numpy as np
from scipy.fft import rfft, rfftfreq

fs = 100                                    # samples per second
t = np.arange(0, 2, 1 / fs)                 # 2 seconds -> 200 samples
x = 1.0 * np.sin(2 * np.pi * 5 * t) + 0.5 * np.sin(2 * np.pi * 12 * t)

X = rfft(x)
freqs = rfftfreq(x.size, d=1 / fs)
amplitude = 2 * np.abs(X) / x.size          # scale to the sine amplitudes

print("number of bins:", X.size, " resolution:", freqs[1], "Hz")
top = np.argsort(amplitude)[-2:][::-1]
for i in top:
    print(f"{freqs[i]:5.1f} Hz  amplitude {amplitude[i]:.3f}")
number of bins: 101  resolution: 0.5 Hz
  5.0 Hz  amplitude 1.000
 12.0 Hz  amplitude 0.500

The FFT recovers both frequencies and their amplitudes exactly, because each tone fits a whole number of cycles in the 2-second window.

The key functions

Function Input → output
fft(x) / ifft(X) complex FFT and its inverse, all frequencies
rfft(x) / irfft(X) for real signals, non-negative frequencies only
fftfreq(n, d) / rfftfreq(n, d) frequency of each bin (d = sample spacing)
fftshift(X) reorder so frequency 0 is in the middle (for plotting)
fft2, fftn 2-D and n-D transforms (images, volumes)
dct, dst cosine / sine transforms (used in JPEG and MP3)

Frequency resolution is fs / n — the sampling rate divided by the number of samples. A longer recording gives finer resolution.

Plotting a spectrum

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt
from scipy.fft import rfft, rfftfreq

rng = np.random.default_rng(4)
fs = 500
t = np.arange(0, 1, 1 / fs)
x = (np.sin(2 * np.pi * 50 * t) + 0.6 * np.sin(2 * np.pi * 120 * t)
     + rng.normal(0, 0.8, t.size))

freqs = rfftfreq(t.size, 1 / fs)
amp = 2 * np.abs(rfft(x)) / t.size

fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(7, 5))
ax1.plot(t[:100], x[:100])
ax1.set_title("Time domain: hard to see anything")
ax2.plot(freqs, amp)
ax2.set_title("Frequency domain: two clear peaks")
ax2.set_xlabel("frequency (Hz)")
fig.tight_layout()
plt.show()

strongest = freqs[np.argsort(amp)[-2:]]
print("strongest frequencies:", np.sort(strongest), "Hz")
strongest frequencies: [ 50. 120.] Hz

The noise is spread thinly across all frequencies, while each tone concentrates in one bin, so the tones stand out clearly in the spectrum.

Filtering in the frequency domain

Because the FFT is invertible, you can edit the spectrum and transform back. Zeroing unwanted bins is a quick (if crude) filter:

python · try it yourself
import numpy as np
from scipy.fft import rfft, irfft, rfftfreq

fs = 1000
t = np.arange(0, 1, 1 / fs)
voice = np.sin(2 * np.pi * 3 * t) + 0.5 * np.sin(2 * np.pi * 7 * t)
whine = 0.4 * np.sin(2 * np.pi * 150 * t)
x = voice + whine

X = rfft(x)
freqs = rfftfreq(x.size, 1 / fs)
X[freqs > 50] = 0                            # remove everything above 50 Hz
cleaned = irfft(X, n=x.size)

print(f"max error before: {np.abs(x - voice).max():.4f}")
print(f"max error after : {np.abs(cleaned - voice).max():.1e}")
max error before: 0.4000
max error after : 5.1e-15

Note: Zeroing bins works perfectly here because every tone fits a whole number of cycles. On real signals it causes ringing near sudden changes; a properly designed filter (previous lessons) is usually the better tool.

Spectral leakage and windows

If a tone does not complete a whole number of cycles in the window, its energy "leaks" into neighbouring bins. Multiplying the signal by a smooth window function, such as the Hann window, reduces leakage far from the peak:

python · try it yourself
import numpy as np
from scipy.fft import rfft, rfftfreq
from scipy.signal import windows

fs = 100
t = np.arange(0, 1, 1 / fs)
x = np.sin(2 * np.pi * 10.5 * t)            # 10.5 cycles: not a whole number

freqs = rfftfreq(t.size, 1 / fs)
plain = np.abs(rfft(x))
hann = np.abs(rfft(x * windows.hann(t.size)))

far = freqs >= 20                            # bins far from the tone
print(f"leakage beyond 20 Hz, no window : {plain[far].sum() / plain.sum():.1%}")
print(f"leakage beyond 20 Hz, Hann      : {hann[far].sum() / hann.sum():.1%}")
leakage beyond 20 Hz, no window : 10.8%
leakage beyond 20 Hz, Hann      : 0.1%

Test yourself

What does the Fourier transform tell you about a signal?

  1. Its maximum value
  2. Which frequencies it contains and how strong they are
  3. Where its peaks are in time
  4. Its average

A signal is sampled at 1000 Hz for 2 seconds. What is the frequency resolution of its FFT?

  1. 0.5 Hz
  2. 1 Hz
  3. 2 Hz
  4. 500 Hz

Why use rfft instead of fft for a real-valued signal?

  1. rfft is more accurate
  2. The negative-frequency half is redundant for real input, so rfft computes only the non-negative half
  3. fft doesn't accept real numbers
  4. rfft returns real numbers