# fast fourier transformation question

I was testing fft on mathematica using simple functions and ran into problems.

I first tried a simple cos function with the following code:

f1[x_] := Cos[2 \[Pi]*x];
Sample = Table[f1[x], {x, 0, 2, 1/100}];
fft = Abs[Fourier[Sample]];
p1 = ListLinePlot[fft, PlotRange -> Full, DataRange -> {-1, 1}]



which does give me the graph of two delta functions. Here is my first question: Why do I have to manually adjust DataRange in order for the peak to be at the correct position namely -1 and 1? I then tried the addition of two cos functions and this is where it started to give me problems

f2[x_] := Cos[2 \[Pi]*x] + Cos[\[Pi]*x];
Sample1 = Table[f2[x], {x, 0, 2, 1/100}];
fft1 = Abs[Fourier[Sample1]];
p2 = ListLinePlot[fft1, PlotRange -> Full]


Supposedly it should give me four peaks at -2,-1,1,2 but the graph is not showing so. Where might it go wrong in this case? And what datarange shall i use? • I have put some notes on Fourier here in answer to another question. You may find them helpful. Let me know if you need more.
– Hugh
Jan 28, 2022 at 13:41
• Hugh I have successfully applied your code to simple functions, however it fails for some more complex function, for example a single impulse. I did read through your points but am unsure if i understand them completely, could you have a look at this question pls?mathematica.stackexchange.com/questions/263082/… Feb 4, 2022 at 0:25
• Hugh pls ignore my above question, I just realised I made a stupid mistake. Thanks for your notes, tremendous help! Feb 4, 2022 at 0:43

To see it better, you'd need to set the frequency scale yourself. This is how I would do it. Assume some sampling frequency

fs = 1000;  (*1000 hz. Assumed sampling frequency*)
sample = Table[Cos[2*Pi*100*t], {t, 0, 1 - 1/fs, 1/fs}];
fft = Fourier[sample];
fft = fft[[1 ;; Length[sample]/2 + 1]];
df = fs/Length[sample];
frequencyAxis = Range[0, fs/2, df];
data = Transpose[{frequencyAxis , Abs[fft]}];
ListLinePlot[data, PlotRange -> All] The above shows f at 100 HZ as expected because we used Cos[2*Pi*100*t] as the signal. Now lets add another one at say 200 hz. Just change the line

sample = Table[Cos[2*Pi*100*t] + Cos[2*Pi*200*t], {t, 0, 1 - 1/fs, 1/fs}];


Now you'll get And so on. The units on the x-axis are in Hz. It goes up to half the sampling frequency (Due to Nyquist limit).