0

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:

Stacktrace

Mathematica tries to replace the x from dx with -2pi?
How can i fix this problem?

  • Try a[n_]:=a[n]=2/Pi*Module[{x},Integrate[f[x]*Cos[n*x],{x,0,Pi/2}]]. The problem is that the x in Plot and the x in Integrate interfere, and one can use Module to prevent this. I also added ...:=a[n]=... to store values for a once calculated, otherwise the same computation is repeated again and again. Use Clear[a] to remove such stored values. – user293787 Nov 08 '22 at 19:13
  • Thank you, that fixed my problem. Also thanks for the =a[n]= tip, didn't know that you could do things like that. If you post it as an answer I will accept it :) – thomasweichhart Nov 08 '22 at 19:25
  • Hi, := can lead to unexpected issues. You could either use Module or 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 with Plot or NIntegrate or FindRoot or other numerically intensive functions. – userrandrand Nov 09 '22 at 02:46
  • If you use = then the symbollic evaluation/conversion is done only once when the function is defined. – userrandrand Nov 09 '22 at 02:48
  • However, when using = you need to use variables that have not been assigned values. For example, it will not work the way you might want if you do x=1;f[x_]=x; – userrandrand Nov 09 '22 at 02:51
  • One other issue is that a[n] is evaluated symbolically and you will have to compute the limit of a[n] when n is close to zero either using Normal@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) or Limit[a[n], n -> 0] which in my past experience Limit was slow but the computation was quick in this case. – userrandrand Nov 09 '22 at 02:57

1 Answers1

1

The problem is that the x in Plot and the x in Integrate interfere.

To avoid this problem, use Module:

a[n_] := 2/Pi*Module[{x},Integrate[f[x]*Cos[n*x],{x,0,Pi/2}]];

It can also be useful to memoize values, as follows:

a[n_] := a[n] = 2/Pi*Module[{x},Integrate[f[x]*Cos[n*x],{x,0,Pi/2}]];
user293787
  • 11,833
  • 10
  • 28