Edit: 2025-05-08
''' title : python-fft-301.py author : Neil Rieck created: 2025-05-08 ref : https://www.geeksforgeeks.org/how-to-extract-frequency-associated-with-fft-values-in-python/ notes : 1) FFT (Fast Fourier Transform) is used to convert a signal from the time-domain
to the frequency-domain 2) python2 had no support for arrays so developers employed "numpy" 3) python3 does support arrays via "import arrays" (not used here) 4) FFT routines are available in both "numpy" and "scipy"
(this simple demo employs the fft method found in "numpy")
5) notice how the numpy arrays are added together WITHOUT using some kind of iterator (very cool) ''' import numpy as np import matplotlib.pyplot as plt # Sampling rate sr = 1000 # Duration in seconds T = 1 # Number of samples N = sr * T # Time vector t = np.linspace(0, T, N, endpoint=False) # Signal: sum of three sine waves f1 = 5 f2 = 10 f3 = 15 signal1 = 1.0 * np.sin(2 * np.pi * f1 * t) signal2 = 0.9 * np.sin(2 * np.pi * f2 * t) signal3 = 0.8 * np.sin(2 * np.pi * f3 * t) signal = signal1 + signal2 + signal3 # Compute the FFT fft_signal = np.fft.fft(signal) # Compute the frequencies corresponding to the FFT coefficients freqs = np.fft.fftfreq(N, 1/sr) # Plot the signals collection = [] collection.append(signal1) collection.append(signal2) collection.append(signal3) collection.append(signal) for idx, temp in enumerate(collection): plt.plot(temp) plt.xlabel('Time') plt.ylabel('Magnitude') plt.title(f'Signal: {idx + 1}') plt.grid(True) plt.show() # Plot the magnitude of the FFT plt.plot(freqs[:N//2], np.abs(fft_signal)[:N//2]) plt.xlabel('Frequency (Hz)') plt.ylabel('Magnitude') plt.title('FFT of the signal') plt.grid(True) plt.show() # this is the last line