Help with Fourier Coefficients

Here is a function for which we wish to find the Fourier sine series.
x for 0<x<Pi/2
f(x)=
Pi-x for Pi/2<x<Pi

In[1]:=

  Clear[p1,p2,fgraph]
  p1=Plot[x,{x,0,Pi/2},DisplayFunction->Identity];
  p2=Plot[Pi-x,{x,Pi/2,Pi},DisplayFunction->Identity];
  fgraph=Show[p1,p2,DisplayFunction->$DisplayFunction,
  AspectRatio->Automatic,
  Ticks->{{Pi/2,Pi},Automatic}];

When we found Fourier sine coefficients in the past we did something like this. Do not evaluate the next cell, it is a text cell.

Clear[b]
b[n_]:=(2/Pi)(Integrate[x Sin[n x],{x,0,Pi/2}]+
Integrate[(Pi-x) Sin[n x],{x,Pi/2,Pi}])
Table[b[k],{k,1,10}]

Now we will use this

In[2]:=

  Clear[b]
  b[n_]:=b[n]=(2/Pi)(Integrate[x Sin[n x],{x,0,Pi/2}]+
  Integrate[(Pi-x) Sin[n x],{x,Pi/2,Pi}])
  Table[b[k],{k,1,10}]

Out[2]=

   4       -4        4        -4         4
  {--, 0, ----, 0, -----, 0, -----, 0, -----, 0}
   Pi     9 Pi     25 Pi     49 Pi     81 Pi

Why the extra b[n]= ?
This asks Mathematica to not only define b[n] as stated but to also store in memory ("remember", if you will) the value of b[n] it calculates for each value of n. In this manner, when you use b[n] in the future, the calculation will be much quicker.

There is one danger here and you MUST be aware of it. If you do a problem later and wish to calculate new coefficients b[n], you must clear the old coeffients using
Clear[b]
before calculating the new values. If not, the new definition will use the old values of the b[n].

Recall the old b[n] above:

In[3]:=

  Table[b[n],{n,1,10}]

Out[3]=

   4       -4        4        -4         4
  {--, 0, ----, 0, -----, 0, -----, 0, -----, 0}
   Pi     9 Pi     25 Pi     49 Pi     81 Pi

In[4]:=

  b[n_]:=b[n]=n
  Table[b[n],{n,1,10}]

Out[4]=

   4       -4        4        -4         4
  {--, 0, ----, 0, -----, 0, -----, 0, -----, 0}
   Pi     9 Pi     25 Pi     49 Pi     81 Pi

In[5]:=

  Clear[b]
  b[n_]:=b[n]=n
  Table[b[n],{n,1,10}]

Out[5]=

  {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

See the difference?

Up to PDE Tips