To perform a Fast Fourier Transform (FFT) and its inverse (IFFT) in Python, you can use the library, which provides efficient implementations for these operations. Below is an example of how you might use to compute the FFT and IFFT:
numpy
numpy.fft
python
import numpy as np
import matplotlib.pyplot as plt
# Sample data: a simple sinusoidal wave
# You can replace this with your actual data
t = np.linspace(0, 1, 500) # 1 second of data at 500 Hz
freq = 5 # Frequency of the sine wave
sample_signal = np.sin(2 * np.pi * freq * t)
# Compute the FFT of the sample signal
fft_result = np.fft.fft(sample_signal)
# Compute the frequencies for the x-axis
frequencies = np.fft.fftfreq(len(sample_signal), t[1] - t[0])
# Compute the IFFT to recover the original signal
recovered_signal = np.fft.ifft(fft_result)
# Plot the original, the magnitude of the FFT, and the recovered signal
plt.figure(figsize=(14, 8))
plt.subplot(3, 1, 1)
plt.plot(t, sample_signal)
plt.title("Original Signal")
plt.xlabel("Time (s)")
plt.ylabel("Amplitude")
plt.subplot(3, 1, 2)
plt.plot(frequencies, np.abs(fft_result))
plt.title("Magnitude of FFT")
plt.xlabel("Frequency (Hz)")
plt.ylabel("Magnitude")
plt.xlim(0, 50) # Limit x-axis for better visualization
plt.subplot(3, 1, 3)
plt.plot(t, recovered_signal.real) # Use `.real` to show only the real part (it should be real)
plt.title("Recovered Signal (IFFT)")
plt.xlabel("Time (s)")
plt.ylabel("Amplitude")
plt.tight_layout()
plt.show()
Explanation:
Original Signal: Generating a simple sine wave signal for demonstration. You can replace this with your own data.
FFT Computation: Using np.fft.fft to compute the discrete Fourier Transform of the signal. The result is a complex number representing the amplitude and phase information of frequency components present in the signal.
Frequency Components: Using np.fft.fftfreq to compute the frequencies corresponding to each FFT result.
IFFT Computation: Using np.fft.ifft to perform the inverse transformation to recover the original signal from its frequency domain representation.
Plotting: Visualizing the original time-domain signal, the magnitude of the FFT, and the recovered signal from IFFT.
This script shows how to apply FFT and IFFT and visualize the results with plots. You can replace the sample signal with your own data to analyze its frequency domain characteristics.