# Fourier series for a function

I am trying to calculate the fourier series of $$f(x)=\sin x$$ for $$0 and $$f(x)=0$$ for $$-\pi and make the plots. I tried

f[x_] = If[x > 0, Sin[x], 0];
a[n_] := (2/L)*Integrate[f[x]*Cos[2 n*Pi*x/L], {x, -L/2, L/2}]
a[0] = (1/L)*Integrate[f[x], {x, -L/2, L/2}]
b[n_] := (2/L)*Integrate[f[x]*Sin[2 n*Pi*x/L], {x, -L/2, L/2}]
F[x_, N_] :=
a[o] + Sum[a[n]*Cos[2 n*Pi*x/L] + b[n]*Sin[2 n*Pi*x/L], {n, 1, N}]
p[N_, a_] :=
Plot[Evaluate[F[x, N]], {x, -a, a}, PlotRange -> All,
PlotPoints -> 200]
L = 2Pi;
a[n]
a[0]
b[n]
p[20, 1]




but the Plot doesn't seems correct. Then, for $$f(x)=0?.$$ What about the converge of the series?

• Move L = 2Pi; from the bottom of your code to the top and in your definition of F[x_,N_] change a[o] to a[0] and that will fix two of your problems.
– Bill
Commented Jan 16, 2020 at 17:13
• Have you seen FourierSeries and FourierCoefficient? Commented Jan 16, 2020 at 17:52

You can just use FourierSeries

ClearAll[x]
nTerms = 10;
f[x_] := Piecewise[{{Sin[x], 0 < x < Pi}, {0, -Pi < x < 0}}]
series = ExpToTrig[FourierSeries[f[x], x, nTerms]]


$$\frac{\sin (x)}{2}-\frac{2 \cos (2 x)}{3 \pi }-\frac{2 \cos (4 x)}{15 \pi }-\frac{2 \cos (6 x)}{35 \pi }-\frac{2 \cos (8 x)}{63 \pi }-\frac{2 \cos (10 x)}{99 \pi }+\frac{1}{\pi }$$

Manipulate[
Module[{series},
series = ExpToTrig[FourierSeries[f[x], x, nTerms]];
Grid[{
{series},
{Plot[series, {x, -a, a}, ImageSize -> 400]}
}, Frame -> All]
]
,
{{nTerms, 4, "How many terms?"}, 1, 10, 1, Appearance -> "Labeled"},
{{a, Pi, "Range?"}, Pi/10, 5 Pi, Pi/10, Appearance -> "Labeled"},
ContinuousAction -> False,
TrackedSymbols :> {a, nTerms},
Initialization :>
(f[x_] := Piecewise[{{Sin[x], 0 < x < Pi}, {0, -Pi < x < 0}}])
]
`

There is also lots of Fourier series animations here, all done using Mathematica.