I am trying to Find the Fourier series representation for n number of harmonics of a discrete time data set. The data is not originally periodic, so I performed a periodic extension on the data set and the result can be seen in the waveform below.
I have tried to replicate the solution in this question : Calculate the Fourier series with the trigonometry approach However The results I received did not produce a proper output as can be seen in the pictures below. It seems that the computation simply outputs an offset version of the original signal.
The data set I am working with is a numpy array with 4060 elements. How can I properly compute and graph the Fourier series decomposition of a discrete data set?
Here is the code i used, it is almost identical to that in the example referred to in the link, except changes have been made to accommodate my own signal data.
# dat is a list with the original non periodic data
# persig is essentially dat repeated over several periods
# Define "x" range.
l = len(persig)
x = np.linspace(0,1,l)
print len(x)
# Define "T", i.e functions' period.
T = len(dat)
print T
L = T / 2
# "f(x)" function definition.
def f(x):
persig = np.asarray(persig)
return persig
# "a" coefficient calculation.
def a(n, L, accuracy = 1000):
a, b = -L, L
dx = (b - a) / accuracy
integration = 0
for x in np.linspace(a, b, accuracy):
integration += f(x) * np.cos((n * np.pi * x) / L)
integration *= dx
return (1 / L) * integration
# "b" coefficient calculation.
def b(n, L, accuracy = 1000):
a, b = -L, L
dx = (b - a) / accuracy
integration = 0
for x in np.linspace(a, b, accuracy):
integration += f(x) * np.sin((n * np.pi * x) / L)
integration *= dx
return (1 / L) * integration
# Fourier series.
def Sf(x, L, n = 5):
a0 = a(0, L)
sum = np.zeros(np.size(x))
for i in np.arange(1, n + 1):
sum += ((a(i, L) * np.cos((i * np.pi * x) / L)) + (b(i, L) * np.sin((i * np.pi * x) / L)))
return (a0 / 2) + sum
plt.plot(x, f(x))
plt.plot(x, Sf(x, L))
plt.show()