0
0
SciPydata~5 mins

FFT computation (fft) in SciPy

Choose your learning style9 modes available
Introduction

FFT helps us quickly find the frequencies inside a signal. It turns time data into frequency data.

You want to find the main tones in a sound recording.
You need to analyze the heartbeat pattern from sensor data.
You want to detect repeating patterns in stock prices.
You want to compress data by focusing on important frequencies.
Syntax
SciPy
from scipy.fft import fft

result = fft(data)

data is your input signal, usually a list or array of numbers.

The output result is a complex array showing frequency info.

Examples
Basic example: FFT of a simple array of 4 numbers.
SciPy
from scipy.fft import fft
import numpy as np

x = np.array([1, 2, 3, 4])
result = fft(x)
print(result)
FFT of a sine wave with frequency 5 Hz, showing first 10 frequency components.
SciPy
from scipy.fft import fft
import numpy as np

x = np.sin(2 * np.pi * 5 * np.linspace(0, 1, 100))
result = fft(x)
print(result[:10])
Sample Program

This program creates a signal with two sine waves at 5 Hz and 20 Hz. It uses FFT to find these frequencies and prints their amplitudes.

SciPy
from scipy.fft import fft
import numpy as np

# Create a signal with two frequencies
fs = 100  # Sampling rate 100 Hz
T = 1.0 / fs  # Sampling interval
N = 100  # Number of samples

# Time vector
x = np.linspace(0.0, (N-1)*T, N, endpoint=True)

# Signal: sum of 5 Hz and 20 Hz sine waves
y = np.sin(2*np.pi*5*x) + 0.5*np.sin(2*np.pi*20*x)

# Compute FFT
yf = fft(y)

# Compute frequency bins
xf = np.fft.fftfreq(N, T)[:N//2]

# Print frequencies with highest amplitudes
amplitudes = np.abs(yf[:N//2])

# Find top 2 frequencies
top_indices = amplitudes.argsort()[-2:][::-1]

for i in top_indices:
    print(f"Frequency: {xf[i]:.1f} Hz, Amplitude: {amplitudes[i]:.2f}")
OutputSuccess
Important Notes

The FFT output is complex numbers; use abs() to get amplitude.

Frequency bins can be found with np.fft.fftfreq() using sample spacing.

FFT works best when the number of samples is a power of two, but it can handle others too.

Summary

FFT changes time data into frequency data quickly.

Use scipy.fft.fft() to compute FFT in Python.

Look at the amplitude to find strong frequencies in your signal.