# Fourier series using DFT

I am trying a simple example to do a discrete Fourier transform. My goal is to use DFT to find the frequencies that have built the time signal and then to a good approximation, use DFT data to find fourier series. Further, I have plan to use Fourier series to do extrapolation of the original time signal.

This is the code

timeData = Table[Sin[x], {x, 0, 10, 0.1}];

n = Length[timeData];

(*Compute the DFT*)
dftData = Fourier[timeData];

(*Only use the first half of the DFT coefficients*)
halfN = Floor[n/2] + 1;

(*Define the Fourier series function using the relevant frequencies*)
fourierSeries[t_] :=
dftData[[1]]/Sqrt[n] +
1/Sqrt[n]  Sum[
2  (Re[dftData[[k + 1]]]  Cos[2  Pi  k  t/n] -
Im[dftData[[k + 1]]]  Sin[2  Pi  k  t/n]), {k, 1, halfN}]

(*Create the discrete data plot*)
discretePlot =
ListPlot[timeData, PlotStyle -> {Red, PointSize[Medium]},
AxesLabel -> {"Sample Index", "Amplitude"}];

(*Create the continuous Fourier series plot*)
continuousPlot =
Plot[fourierSeries[t], {t, 0, 150}, PlotRange -> All,
PlotStyle -> Blue, AxesLabel -> {"Sample Index", "Amplitude"}];

(*Combine the plots*)
Show[continuousPlot, discretePlot,
PlotLabel -> "Time-Domain Signal and Fourier Series",
GridLines -> Automatic]


and this is the plot I am getting

• Maybe find frequencies first, then use that to sample over proper periods. Sampling over a non-period is going to make it a period, which can result in weird artifacts. Commented Jul 18 at 4:07

As Daniel Lichtblau already mentioned, you must sample over an integre number of periods. Otherwise, the start and end gets distorted.

Then you have to remember how the fft coefficients are stored. At position 1 we have the DC component. Then comes the lowest positive frequency coefficient. Then the second lowest up to the highest. If the length of the data we have one highest coefficient, if odd we have two (note that both base functions of highest frequency will evaluate to the same numbers: 1 or -1). Then come the negative frequency coefficients from the highest to the lowest. If the original data is real, the negative frequency coefficients are the conjugate of the positive ones.

With the above and the x values of the data= 1,2,3... we have (note that we need a correction to the simple formula below for the single highest frequency in case the data length is even ):

dat = Table[Sin[x], {x, 0, 2 Pi, .1}];
n = Length[dat];
fft = Fourier[dat];
bas = Table[
Exp[ -2 Pi  I  If[i <= (n + 1)/2, (i - 1), -(n + 1 - i)] (x - 1)/
n], {i, n}];
fun[x_] = (bas . fft +
If[EvenQ[n],
fft[[1 + n/2]] (E^(-I \[Pi] (-1 + x)) - E^(I \[Pi] (-1 + x)))/
2, 0])/Sqrt[n] // Re;
Plot[{fun[x]}, {x, 1, n}, Epilog -> Point[Transpose[{Range[n], dat}]]]