Fourier Series

Fourier Series are a projection method. Here's some code for calculating the coefficients:

> fe := proc(f) fnormal(evalf(f)); end:
> a := proc(f, n)
if n=0 then fe((1/(2*Pi))*Int(f, x=-Pi..Pi));
else fe((1/Pi)*Int( f*cos(n*x), x=-Pi..Pi));
fi;
end:
> b := proc(f, n)
if n=0 then 0;
else fe((1/Pi)*Int( f*sin(n*x), x=-Pi..Pi));
fi;
end:
> fs := (f, n) -> sum('a(f, k)*cos(k*x) + b(f, k)*sin(k*x)', k=0..n);

Note that we have chosen to convert the coefficients to floating-point form, to standardize the interval length [to the circumference of the unit circle], and to make the coefficients functions [whose arguments are expressions]. Other choices also work. Here are some examples of the result:

> fs1 := fs(x, 10);
           fs1 := 1.999999999 sin(x) - .9999999999 sin(2 x)

                  + .6666666664 sin(3 x) - .4999999999 sin(4 x)

                  + .3999999998 sin(5 x) - .3333333332 sin(6 x)

                  + .2857142856 sin(7 x) - .2499999999 sin(8 x)

                  + .2222222222 sin(9 x) - .1999999999 sin(10 x)
> plot({ x, fs1 }, x=-Pi .. Pi, scaling=constrained);
fourier graph 1
> fs2 := fs(x^2,4):

       fs2 := 3.289868133 - 3.999999998 cos(x) + .9999999999 cos(2 x)

              - .4444444445 cos(3 x) + .2499999999 cos(4 x)
> plot({ x^2, fs2 }, x=-Pi .. Pi, scaling=constrained);
fourier graph 2
> f3 := x -> signum(sin(x)): > fs3 := fs(f3(x),10);

             fs3 := 1.273239544 sin(x) + .4244131814 sin(3 x)

                    + .2546479089 sin(5 x) + .1818913635 sin(7 x)

                    + .1414710605 sin(9 x)
> plot({ f3(x), fs3 }, x=-2*Pi .. 2*Pi, scaling=constrained);
fouier graph 3
>fsexp := fs(exp(x), 10): fsexp;
               3.676077909 - 3.676077910 cos(x) + 3.676077910 sin(x)
          
                    + 1.470431164 cos(2 x) - 2.940862328 sin(2 x)

                    - .7352155817 cos(3 x) + 2.205646746 sin(3 x)

                    + .4324797542 cos(4 x) - 1.729919016 sin(4 x)

                    - .2827752238 cos(5 x) + 1.413876119 sin(5 x)

                    + .1987069140 cos(6 x) - 1.192241484 sin(6 x)

                    - .1470431164 cos(7 x) + 1.029301815 sin(7 x)

                    + .1131100895 cos(8 x) - .9048807162 sin(8 x)

                    - .08966043682 cos(9 x) + .8069439313 sin(9 x)

                    + .07279362198 cos(10 x) - .7279362198 sin(10 x)
> plot({ exp(x), fsexp }, x=-Pi .. Pi, color=red);
fsexp graph