(* \input mathlily
\heading{Wave reflection; piecewise defined functions}
\synopsis{The wave equation on $0<x<\infty$ with $u(0,t)=0$
(the infinite vibrating string) is solved by using the odd extension
of the initial data in D'Alembert's formula.
To demonstrate this we need to work around some of 
\'Mathematica\/''s obtuseness in dealing with 
piecewise defined functions.}
\section{Defining, differentiating, and plotting an odd extension} *)


 (* The \|Sign| function equals $+1$ when its argument is positive,
$-1$ when the argument is negative, and 0 when the argument is 0. 
A function of the form \|Sign[x] * |$<$function of \|Abs[x]| only$>$ 
is odd. *)

(* So, here is the odd extension of a nice, sharply peaked function: *)

F[x_] := Sign[x]/(1+(Abs[x]-4)^2)
Plot[F[x], {x, -10, 10}]

(* Let's calculate and plot its derivative. *)

D[F[x], x]
Plot[%, {x, -10, 10}]

(* Oops!  \'Mathematica\/' does not know how to differentiate its
own functions, \|Abs| and \|Sign|.  (Indeed, these functions do not
\'have\/' derivatives at $x=0$.  However, \'Mathematica\/' does not 
seem to understand that they \'do\/' have very simple derivatives when
$x$ is \'not\/'~0.)  For that reason, it can't plot the derivative. *)

(* Let's try defining our own absolute value and sign functions. *)  
 
abs[x_] := If[Positive[x], x, -x]
D[abs[x], x]
Plot[%, {x, -10, 10}]

(* This derivative is actually equal to the sign function, so \dots\ *)

sign[x_] := D[abs[x], x]
sign[-1]

(* Oops!  We told the program to substitute $-1$ for $x$ \'before\/'
differentiating, which is nonsense.  Let's try again \'without\/' the
colon. *)

Clear[sign]
sign[x_] = D[abs[x], x]
sign[-1] 

(* Now let's try again to define our function. *)

f[x_] := sign[x]/(1+(abs[x]-4)^2)
D[f[x], x]
Plot[%, {x, -10, 10}]

(* Alternatively, we can work with the built-in functions as long as
we can, then substitute our versions when we need them: *)

D[F[x+2], {x,2}]
% /. {Abs->abs, Sign->sign}
Plot[%, {x, -10, 10}]

(* The wave equation is still formally satisfied even when the
derivatives can't be evaluated: *)

 D[F[x-t], {x,2}] - D[F[x-t], {t,2}] 


(* \section{Demonstration} *)

 
(* Let us use our function $f$ as the initial value, and assume that
the initial time derivative is zero. *)

Do[Plot[(F[x+t]+F[x-t])/2, {x,-10,10}, PlotRange->{-1,1}], {t, 0,10}]
(* \'Animate this.' *)

(* We see the peak and its upside-down mirror image each divide into 
two pulses, moving in opposite directions. *)

(* Now let's look only at the physical region. *)

Do[Plot[(F[x+t]+F[x-t])/2, {x,0,10}, PlotRange->{-1,1}], {t, 0,10}]
(* \'Animate this.' *)

(* The left-moving pulse bounces off the wall and escapes to the right.
The end of the ``string'' remains tied down at~0, as the boundary 
condition requires. *)

(* \endlily *) 




