When i try to evaulate h at vaule (for example 0), i get a result. When i directly plot the output of h, it also works, but when i try to plot h itself i get a very weird error:
f[x_] :=
Piecewise[{{0, -\[Pi] <= x <= -\[Pi]/2}, {2 x + \[Pi], -\[Pi]/2 <=
x <= 0}, {\[Pi] - 2 x,
0 <= x <= \[Pi]/2}, {0, \[Pi]/2 <= x <= \[Pi]}}]
g[x_] := \[Pi] - 2 x
a[n_] := 2/\[Pi]*Integrate[f[x]*Cos[n*x], {x, 0, \[Pi]/2}]
h[x_] := a[0]/2 + Sum[a[i]*Cos[x*i], {i, 10}]
h[0]
Plot[{f[x], g[x], h[x] }, {x, -2 \[Pi], 2 \[Pi]}]
"Invalid integration variable or limit(s) in {-6.28293,0,\[Pi]/2}"
When you take a look at the stacktrace, it shows this:
Mathematica tries to replace the x from dx with -2pi?
How can i fix this problem?

a[n_]:=a[n]=2/Pi*Module[{x},Integrate[f[x]*Cos[n*x],{x,0,Pi/2}]]. The problem is that thexinPlotand thexinIntegrateinterfere, and one can useModuleto prevent this. I also added...:=a[n]=...to store values foraonce calculated, otherwise the same computation is repeated again and again. UseClear[a]to remove such stored values. – user293787 Nov 08 '22 at 19:13:=can lead to unexpected issues. You could either useModuleor consider replacing all the:=with=. The pattern matching still works if you use=.:=is important if you really do not want the right hand side to evaluate right away.:=can also lead to performance loss because the symbolic expression on the right is computed each time the function is called. That can be lengthy when using the function withPlotorNIntegrateorFindRootor other numerically intensive functions. – userrandrand Nov 09 '22 at 02:46=then the symbollic evaluation/conversion is done only once when the function is defined. – userrandrand Nov 09 '22 at 02:48=you need to use variables that have not been assigned values. For example, it will not work the way you might want if you dox=1;f[x_]=x;– userrandrand Nov 09 '22 at 02:51a[n]is evaluated symbolically and you will have to compute the limit ofa[n]whennis close to zero either usingNormal@Series[a[n], {n, 0, 0}](I vaguely remember a case where I had to extend the series to next order to get the first order correct) orLimit[a[n], n -> 0]which in my past experienceLimitwas slow but the computation was quick in this case. – userrandrand Nov 09 '22 at 02:57