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.

  • Intermédiaire
  • 2 min de lecture
  • 1 exemple exécutable
Ce que vous allez apprendre
  • 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

Découvrez FFT in Python with NumPy avec un exemple pratique modifiable et exécutable en ligne.

Points clés

  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.

Quand l’utiliser ?

  • Solve equations, integrals and differential equations in a few lines.
  • Fit models to measured data and analyse signals in science and engineering classes.
  • Check homework answers numerically and see where a hand calculation went wrong.

Code d’exemple

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}")
Obtenir un bouton Run pour cet exemple

Résultat de l’exécution

Number of frequency bins: 501
Frequency resolution: 1.0 Hz
50 Hz  amplitude 1.00
120 Hz  amplitude 0.50

Explication du code

Cet exemple montre FFT in Python with NumPy en pratique. Modifiez les valeurs d’entrée et relancez le code pour voir ce qui change.

Modifiez les valeurs et exécutez le programme avec le compilateur Python en ligne CodeUtility, sans installation locale.

Exercices d’approfondissement

Essayez de modifier le code en suivant les pistes ci-dessous. Changer le code et observer le résultat vous fera bien mieux comprendre la leçon que la simple lecture.

  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.
Exécuter dans le compilateur Python →

Leçon terminée ?

Marquez-la comme apprise pour suivre votre progression.

Outils pour cette leçon