python code for Fast Fourier Transform
- User
python code for Fast Fourier Transform
Assistant
Here is an example of Python code that uses the Fast Fourier Transform (FFT) algorithm to transform a signal from the time domain to the frequency domain:
codeimport numpy as np def fft(x): """ Fast Fourier Transform (FFT) algorithm Parameters: x (numpy array): input signal in the time domain Returns: X (numpy array): output signal in the frequency domain """ N = len(x) if N <= 1: return x elif N % 2 == 0: even = fft(x[0::2]) odd = fft(x[1::2]) T = np.exp(-2j * np.pi * np.arange(N) / N) return np.concatenate((even + T[:N // 2] * odd, even + T[N // 2:] * odd)) else: raise ValueError("Length of input signal must be a power of 2") # Example usage: t = np.linspace(0, 1, 1024) # time array x = np.sin(2 * np.pi * 10 * t) + 0.5 * np.sin(2 * np.pi * 20 * t) # signal X = fft(x) # perform FFT freq = np.fft.fftfreq(len(X), d=t[1] - t[0]) # frequency array # Plot the frequency spectrum import matplotlib.pyplot as plt plt.plot(freq, np.abs(X)) plt.xlabel('Frequency') plt.ylabel('Amplitude') plt.show()This code defines a function
fftthat takes a numpy arrayxas input, which represents a signal in the time domain. The function returns the FFT of the input signal, which is a numpy arrayXthat represents the signal in the frequency domain.The FFT algorithm is implemented using a recursive approach, which is efficient for large input signals. The basic idea is to divide the input signal into two smaller signals, one containing the even-indexed samples and the other containing the odd-indexed samples. The FFT of each smaller signal is computed recursively, and then the two results are combined using a set of complex exponentials to form the final FFT.
In the example usage, we create a time array
tand a signalxthat is a sum of two sinusoids with frequencies 10 Hz and 20 Hz. We then perform the FFT using the function and plot the frequency spectrum using matplotlib.