FFT helps us quickly find the hidden frequencies in a signal. It turns time data into frequency data so we can understand patterns better.
0
0
FFT with np.fft module in NumPy
Introduction
Analyzing sound waves to find musical notes.
Checking vibrations in machines to detect problems.
Studying heartbeats to find irregular rhythms.
Finding repeating patterns in stock prices.
Syntax
NumPy
numpy.fft.fft(a, n=None, axis=-1, norm=None)
a is the input array (your signal data).
n is the length of the FFT (optional, pads or trims data).
Examples
Basic FFT on a small array of 4 numbers.
NumPy
import numpy as np x = np.array([1, 2, 3, 4]) fft_result = np.fft.fft(x)
FFT with zero-padding to length 8 for higher frequency resolution.
NumPy
fft_result = np.fft.fft(x, n=8)FFT along the first axis (default for 1D arrays).
NumPy
fft_result = np.fft.fft(x, axis=0)Sample Program
This program creates a signal with two sine waves at 50 Hz and 120 Hz. It uses FFT to find these frequencies and prints their values and amplitudes. It also plots the original signal and the frequency spectrum.
NumPy
import numpy as np import matplotlib.pyplot as plt # Create a signal with two frequencies sampling_rate = 1000 # samples per second T = 1.0 / sampling_rate # sample spacing x = np.linspace(0.0, 1.0, sampling_rate, endpoint=False) signal = 0.5 * np.sin(50.0 * 2.0 * np.pi * x) + 0.3 * np.sin(120.0 * 2.0 * np.pi * x) # Compute FFT fft_values = np.fft.fft(signal) # Compute frequencies for x-axis freqs = np.fft.fftfreq(len(signal), T) # Take only the positive half of frequencies and amplitudes positive_freqs = freqs[:len(freqs)//2] positive_fft = np.abs(fft_values[:len(fft_values)//2]) # Print main frequency peaks peak_indices = positive_fft.argsort()[-2:][::-1] for i in peak_indices: print(f"Frequency: {positive_freqs[i]:.1f} Hz, Amplitude: {positive_fft[i]:.2f}") # Plot the signal and its FFT plt.subplot(2, 1, 1) plt.plot(x, signal) plt.title('Original Signal') plt.xlabel('Time [s]') plt.ylabel('Amplitude') plt.subplot(2, 1, 2) plt.stem(positive_freqs, positive_fft, use_line_collection=True) plt.title('FFT Magnitude') plt.xlabel('Frequency [Hz]') plt.ylabel('Magnitude') plt.tight_layout() plt.show()
OutputSuccess
Important Notes
FFT output is complex numbers; use np.abs() to get amplitude.
Frequencies can be positive or negative; usually, we look at positive frequencies only.
Sampling rate affects frequency resolution and max frequency you can detect.
Summary
FFT converts time signals into frequency signals.
Use np.fft.fft() to perform FFT on data arrays.
Analyze the magnitude of FFT to find main frequencies in your data.