# Fast fourier coefficients for a long sum

I have a very long expression involving a sum of exponentials, say:

Sum[(RandomReal[] + RandomReal[] a) Exp[2 I ii x Pi], {ii, -10, 10}]


I want the fastest way to get the list of Fourier coefficients. The Naive ways are pretty time-consuming:

Table[FourierCoefficient[f, x, ii], {ii, -10, 10}]; // Timing (*3.49906 *)
Table[1/(2 Pi) Integrate[f Exp[-ii I x], {x, -Pi, Pi}], {ii, -10,
10}]; // Timing (*7.3649*)


Is there a way to make it faster?

A form of Coefficient would do, but requires a special case for ii=0:

fcoeff[a_, 0] := a /. E^(_. x) -> 0;
fcoeff[a_, ii_] := Coefficient[a, Exp[2 I ii x Pi]]


Assemble your expression (a bit abbreviated here):

X = Sum[(RandomReal[] + RandomReal[] a) Exp[2 I ii x Pi], {ii, -2, 2}]
(*    0.0403894 + 0.340659 a +
(0.818202 + 0.041396 a) E^(-2 I π x) +
(0.676596 + 0.0681271 a) E^(2 I π x) +
(0.446339 + 0.169486 a) E^(-4 I π x) +
(0.67812 + 0.549347 a) E^(4 I π x)        *)


Extract the Fourier coefficients:

Table[fcoeff[X, ii], {ii, -2, 2}]
(*    {0.446339 + 0.169486 a,
0.818202 + 0.041396 a,
0.0403894 + 0.340659 a,
0.676596 + 0.0681271 a,
0.67812 + 0.549347 a}      *)


I am not sure what you want but assuming f is the function you define then

ClearAll[f];
f = Sum[(RandomReal[] + RandomReal[] a) Exp[2 I ii x Pi], {ii, -10,
10}];
ExpToTrig[f] // Simplify


Gives a nice list of Cos and Sin functions. Is this along the correct lines? Are the coefficients of the Cos and Sin what you need?