python-scipyHow can I use Python and SciPy to perform a Fast Fourier Transform?
The Fast Fourier Transform (FFT) is a powerful tool for analyzing signals in the frequency domain. Python and SciPy provide an easy way to perform FFTs. To use SciPy, the following code can be used:
import numpy as np
from scipy.fftpack import fft
# Number of sample points
N = 600
# sample spacing
T = 1.0 / 800.0
x = np.linspace(0.0, N*T, N)
y = np.sin(50.0 * 2.0*np.pi*x) + 0.5*np.sin(80.0 * 2.0*np.pi*x)
yf = fft(y)
This code will create an array of 600 points, spaced 1/800 apart, and create a signal consisting of two sinusoidal waves. The FFT is then applied to the signal with the fft function from SciPy's fftpack submodule.
The output of the FFT is an array of complex numbers, representing the amplitude and phase of each frequency component in the signal. To get the power spectrum of the signal, the magnitude of each complex number can be taken with the np.abs function.
xf = np.linspace(0.0, 1.0/(2.0*T), N//2)
import matplotlib.pyplot as plt
plt.plot(xf, 2.0/N * np.abs(yf[0:N//2]))
plt.grid()
plt.show()
This code will plot the power spectrum of the signal.
Code explanation
**
import numpy as np: imports the numpy library.from scipy.fftpack import fft: imports thefftfunction from SciPy'sfftpacksubmodule.N = 600: sets the number of sample points.T = 1.0 / 800.0: sets the sample spacing.x = np.linspace(0.0, N*T, N): creates an array of 600 points, spaced 1/800 apart.y = np.sin(50.0 * 2.0*np.pi*x) + 0.5*np.sin(80.0 * 2.0*np.pi*x): creates a signal consisting of two sinusoidal waves.yf = fft(y): applies the FFT to the signal.xf = np.linspace(0.0, 1.0/(2.0*T), N//2): creates an array of frequencies.plt.plot(xf, 2.0/N * np.abs(yf[0:N//2])): plots the power spectrum of the signal.
## Helpful links
More of Python Scipy
- How can I use Python and SciPy to find the zeros of a function?
- How can I use Python and Numpy to parse XML data?
- How do I use Python XlsxWriter to write a NumPy array to an Excel file?
- How to use Python, XML-RPC, and NumPy together?
- How can I use Python Numpy to select elements from an array based on multiple conditions?
- How do I use Python Scipy to perform a Z test?
- How can I use Scipy with Python?
- How do I use the scipy ttest_ind function in Python?
- How do I create a 2D array of zeros using Python and NumPy?
- How do I check the version of Python SciPy I'm using?
See more codes...