discrete fourier series coefficients from data points in python

One way to obtain the Discrete Fourier Series coefficients from a set of data points in Python is to use the numpy.fft module, which provides a fast and efficient implementation of the Discrete Fourier Transform.

First, we need to obtain the data points and define the sampling rate:

main.py
import numpy as np

# define the sampling rate
fs = 1000 

# generate some sample data points
t = np.linspace(0, 1, fs, endpoint=False)
x = np.sin(2*np.pi*50*t) + np.sin(2*np.pi*120*t)
185 chars
9 lines

Next, we can use the numpy.fft.fft function to obtain the Discrete Fourier Transform of the data points:

main.py
X = np.fft.fft(x)
18 chars
2 lines

The resulting X array contains the complex Fourier coefficients, where the k-th element of X represents the coefficient X[k] for the k-th frequency component. The frequencies are given by the following formula:

main.py
freqs = np.fft.fftfreq(len(x)) * fs
36 chars
2 lines

To obtain the magnitude of the coefficients, we can take the absolute value:

main.py
mag = np.abs(X)
16 chars
2 lines

Finally, we can plot the magnitude of the coefficients versus the frequency:

main.py
import matplotlib.pyplot as plt

plt.plot(freqs[:fs//2], mag[:fs//2]) # plot the positive half of the spectrum
plt.xlabel('Frequency (Hz)')
plt.ylabel('Magnitude')
plt.show()
175 chars
7 lines

This will give us a plot of the frequency spectrum of the data points.

gistlibby LogSnag