Complete the code to create a simple sine wave signal.
import numpy as np import matplotlib.pyplot as plt # Time array from 0 to 1 second with 500 samples t = np.linspace(0, 1, 500) # Frequency of the sine wave freq = 5 # Create the sine wave signal signal = np.sin(2 * np.pi * freq * [1]) plt.plot(t, signal) plt.title('Sine Wave Signal') plt.xlabel('Time (seconds)') plt.ylabel('Amplitude') plt.show()
The sine wave is created by multiplying the frequency by the time array t. This gives the correct phase for the sine function.
Complete the code to compute the Fourier Transform of the signal.
import numpy as np # Assume signal is defined as a numpy array fourier_transform = np.fft.[1](signal) # Get the magnitude of the transform magnitude = np.abs(fourier_transform)
The np.fft.fft function computes the Fourier Transform of the signal.
Fix the error in the code to plot the frequency spectrum correctly.
import numpy as np import matplotlib.pyplot as plt # Sampling rate and number of samples fs = 500 N = 500 # Frequency array freqs = np.fft.fftfreq(N, 1/[1]) # Fourier Transform of the signal ft = np.fft.fft(signal) plt.plot(freqs, np.abs(ft)) plt.title('Frequency Spectrum') plt.xlabel('Frequency (Hz)') plt.ylabel('Magnitude') plt.show()
The second argument to np.fft.fftfreq is the sample spacing, which is the inverse of the sampling rate fs.
Fill both blanks to create a dictionary of frequencies and their magnitudes for frequencies above zero.
freq_magnitude = {freq: mag for freq, mag in zip(freqs, np.abs(ft)) if freq [1] 0 and freq [2] fs/2}We want frequencies greater than zero and less than the Nyquist frequency (half the sampling rate).
Fill all three blanks to create a normalized frequency magnitude dictionary for positive frequencies.
normalized_freq_mag = {freq: mag/[1] for freq, mag in freq_magnitude.items() if freq [2] 0 and freq [3] fs/2}Normalization is done by dividing by the sum of magnitudes. The frequency conditions filter positive frequencies below Nyquist frequency.
