FFT helps us quickly find the hidden frequencies in a signal. It turns time data into frequency data so we can understand patterns better.
FFT with np.fft module in NumPy
numpy.fft.fft(a, n=None, axis=-1, norm=None)
a is the input array (your signal data).
n is the length of the FFT (optional, pads or trims data).
import numpy as np x = np.array([1, 2, 3, 4]) fft_result = np.fft.fft(x)
fft_result = np.fft.fft(x, n=8)fft_result = np.fft.fft(x, axis=0)This program creates a signal with two sine waves at 50 Hz and 120 Hz. It uses FFT to find these frequencies and prints their values and amplitudes. It also plots the original signal and the frequency spectrum.
import numpy as np import matplotlib.pyplot as plt # Create a signal with two frequencies sampling_rate = 1000 # samples per second T = 1.0 / sampling_rate # sample spacing x = np.linspace(0.0, 1.0, sampling_rate, endpoint=False) signal = 0.5 * np.sin(50.0 * 2.0 * np.pi * x) + 0.3 * np.sin(120.0 * 2.0 * np.pi * x) # Compute FFT fft_values = np.fft.fft(signal) # Compute frequencies for x-axis freqs = np.fft.fftfreq(len(signal), T) # Take only the positive half of frequencies and amplitudes positive_freqs = freqs[:len(freqs)//2] positive_fft = np.abs(fft_values[:len(fft_values)//2]) # Print main frequency peaks peak_indices = positive_fft.argsort()[-2:][::-1] for i in peak_indices: print(f"Frequency: {positive_freqs[i]:.1f} Hz, Amplitude: {positive_fft[i]:.2f}") # Plot the signal and its FFT plt.subplot(2, 1, 1) plt.plot(x, signal) plt.title('Original Signal') plt.xlabel('Time [s]') plt.ylabel('Amplitude') plt.subplot(2, 1, 2) plt.stem(positive_freqs, positive_fft, use_line_collection=True) plt.title('FFT Magnitude') plt.xlabel('Frequency [Hz]') plt.ylabel('Magnitude') plt.tight_layout() plt.show()
FFT output is complex numbers; use np.abs() to get amplitude.
Frequencies can be positive or negative; usually, we look at positive frequencies only.
Sampling rate affects frequency resolution and max frequency you can detect.
FFT converts time signals into frequency signals.
Use np.fft.fft() to perform FFT on data arrays.
Analyze the magnitude of FFT to find main frequencies in your data.
Practice
np.fft.fft() function do in numpy?Solution
Step 1: Understand the purpose of FFT
FFT converts time-domain data into frequency-domain data quickly.Step 2: Identify the function role
np.fft.fft()computes this Fast Fourier Transform on input data.Final Answer:
It computes the Fast Fourier Transform of a signal. -> Option DQuick Check:
FFT = Fast Fourier Transform [OK]
- Confusing FFT with sorting or averaging functions
- Thinking FFT generates random data
- Mixing FFT with statistical calculations
data?Solution
Step 1: Recall numpy FFT syntax
The correct function call isnp.fft.fft()with the data array as argument.Step 2: Check each option
Onlynp.fft.fft(data)matches the correct syntax; others are invalid or incorrect.Final Answer:
np.fft.fft(data) -> Option BQuick Check:
Correct function call = np.fft.fft(data) [OK]
- Swapping function and module order
- Using wrong function names
- Passing wrong argument types
import numpy as np x = np.array([1, 0, 0, 0]) fft_x = np.fft.fft(x) print(np.round(fft_x, 2))
Solution
Step 1: Understand input signal
The input array has one '1' followed by zeros, representing a unit impulse (delta function).Step 2: Compute FFT of impulse
The FFT of a unit impulse of length 4 is [4.+0.j 0.+0.j 0.+0.j 0.+0.j], because the sum of the input is 1 at position 0, but the FFT sums all elements, so the DC component is 4.Final Answer:
[4.+0.j 0.+0.j 0.+0.j 0.+0.j] -> Option CQuick Check:
Impulse FFT = DC component equals sum of input [OK]
- Thinking FFT shows sum only at DC ([4.+0.j 0.+0.j 0.+0.j 0.+0.j])
- Ignoring complex number format
- Misreading array rounding
import numpy as np signal = [1, 2, 3, 4] fft_signal = np.fft.fft(signal, n=-1) print(fft_signal)
Solution
Step 1: Check FFT length parameter
The input signal length is 4, but n=-1 is smaller than input length.Step 2: Understand FFT behavior with n parameter
FFT length n must be at least the input length or zero-padded; smaller n truncates data causing error or unexpected results.Final Answer:
The FFT length n cannot be smaller than the input length. -> Option AQuick Check:
FFT length n ≥ input length [OK]
- Thinking lists are invalid input
- Believing n can be any number
- Assuming print syntax error
noisy_signal. You want to remove high-frequency noise by zeroing FFT components above index 5. Which code correctly applies this filter and returns the cleaned signal?Solution
Step 1: Compute FFT of noisy signal
Usenp.fft.fft(noisy_signal)to get frequency components.Step 2: Zero out high-frequency components
Set FFT values from index 5 onward to zero to remove high frequencies.Step 3: Compute inverse FFT to get cleaned signal
Applynp.fft.ifft()and take real part to get filtered time-domain signal.Final Answer:
fft_vals = np.fft.fft(noisy_signal) fft_vals[5:] = 0 clean_signal = np.fft.ifft(fft_vals).real -> Option AQuick Check:
Zero high freq FFT, then inverse FFT [OK]
- Zeroing low-frequency components instead
- Using ifft before fft
- Not taking real part after inverse FFT
Ready to prove it?
Pass the test and this pattern moves unknown
