calculate frequencies in a time domain in python

To calculate the frequencies in a time domain signal in Python, you can use the fast Fourier transform (FFT) in the numpy library.

Here's an example code snippet:

main.py
import numpy as np

# Generate a sample signal with a frequency of 2 Hz
sample_rate = 100  # Hz
duration = 5  # seconds
num_samples = sample_rate * duration
time = np.linspace(0, duration, num_samples)
signal = np.sin(2 * np.pi * 2 * time)  # 2 Hz sine wave

# Perform the FFT
fft = np.fft.fft(signal)

# Get the frequencies corresponding to each FFT coefficient
freqs = np.fft.fftfreq(num_samples, 1/sample_rate)

# Only keep the positive frequencies and corresponding FFT coefficients
mask = freqs > 0
freqs = freqs[mask]
fft = np.abs(fft[mask])

# Plot the power spectrum
import matplotlib.pyplot as plt
plt.plot(freqs, fft**2)
plt.xlabel('Frequency (Hz)')
plt.ylabel('Power')
plt.show()
691 chars
27 lines

This code generates a 2 Hz sine wave, performs the FFT on the signal, and plots the power spectrum of the resulting FFT coefficients. The frequencies are calculated using np.fft.fftfreq() and correspond to each FFT coefficient. We only keep the positive frequencies and corresponding FFT coefficients, and plot the power spectrum of the FFT coefficients squared.

gistlibby LogSnag