You can use FourierCoefficient
to pre-calculate the Fourier coefficients to arbitrary degree and then use the result very effectively.
There may be some issues with zero-th degree, therefore I excluded this using Piecewise
. Here's the main code block:
f[x_] := Piecewise[{
{-x^3 - 2 x, -2 < x < 0},
{-1 + x, 0 <= x <= 2}},
0
];
Module[{x, fp},
(* Set parameters so that the integration runs
from -2 to 2 *)
fp = {0, -Pi/2};
fc = Piecewise[{
{FourierCoefficient[f[x], x, 0, FourierParameters -> fp], # == 0},
{ComplexExpand@FourierCoefficient[f[x], x, #, FourierParameters -> fp], True}
}] &;
fc = Evaluate /@ fc;
];
The output (fc
) of this is something very unpleasant to look at; however, there's nothing Fourier-related left there, all the hard math has been done already, and only a bunch of elementary functions remain. fc
is now a function of one argument that gives you the n$n$-th Fourier coefficient of f
in no time.
(* Calculate the first 2001 Fourier coefficients *)
AbsoluteTiming[Table[fc[n], {n, -1000, 1000}]] // First
0.777059 seconds
To convert this back to the function, you have to do the partial sum with your hands, for example here are the second, fourth and eighietheightieth partial sums:
myPartialSums = Table[
(* 1/2 andThe Pi/2 compensatecompensates for the custom FourierParameters, see
documentation of FourierSeries/FourierParameters
under "more info" *)
1/2 Re[Sum[fc[k] Exp[PiExp[-Pi/2 I k t], {k, -n, n}]],
{n, {2, 4, 80}}
];
A very large output has been generated,
but we're luckily not interested in it
anyway but would rather plot it
Plot[
{f[t]}~Join~myPartialSums ~Join~ myPartialSums,
{t, -10, 10},
PlotRange -> All,
Evaluated -> True,
PlotStyle -> {Thick, Automatic, Automatic, Automatic}
]