# Derivative from the left and right

I am currently trying to write a script that takes a curve $C$, a starting point $p$ and a direction vector $\vec{v}$ and calculates the path of a beam starting at $p$ in direction $\vec{v}$ when it is reflected on $C$.

The idea is basically: (Numerically) find the (first) crossing point of beam and $C$, calculate tangent in that point, calculate new beam direction, repeat.

Now, if my curve is point-wise not differentiable (in my case: $C$ has "kinks"), I would like to treat it as a limit case where both smooth curves around the kinks are considered, so the calculation forks and I get 2 possible beam pathes. For this, I need the left and the right side derivative of this point. How do I get those in Mathematica?

Also, if somebody knows a better way or this has already been written and is public, I appreciate any clues, of course.

The NumericalCalculus Package already treats this:

Use Scale to specify directional derivatives.

Needs["NumericalCalculus"]
f[x_] := TriangleWave[x];
ND[f[x], {x, 1}, 3/4, Scale -> -1]
ND[f[x], {x, 1}, 3/4, Scale -> 1]
(*
-> -3.99999
3.99999
*)

• One should of course give the usual caveat of numerical differentiation being somewhat unstable, so some care is necessary if using this method. – J. M. will be back soon Jun 4 '12 at 14:34
• @J.M. The problem is that Mma treats numerically some functions it shouldn't. See stackoverflow.com/questions/6326110/… – Dr. belisarius Jun 4 '12 at 14:46
• Great, I thought so :) My functions are not two crazy, mostly piecewise defined straight lines or short polynominals, so both ways should work just fine. – mcandril Jun 5 '12 at 8:53

If your kinked curve is a function that is known to Mathematica or is entirely in terms of functions known to Mathematica, you can go back to using the definition of left and right derivatives, and use Limit[] for the purpose, along with its Direction option:

Plot[TriangleWave[x], {x, 0, 2},
Epilog -> {AbsolutePointSize, Point[{1/4, TriangleWave[1/4]}]}] (* coming from the left *)
Limit[(TriangleWave[1/4 + h] - TriangleWave[1/4])/h, h -> 0, Direction -> 1]
4

(* coming from the right *)
Limit[(TriangleWave[1/4 + h] - TriangleWave[1/4])/h, h -> 0, Direction -> -1]
-4


If your function is an InterpolatingFunction[] or some other black-box function that can only take numerical arguments, different approaches are needed. If that's what you're interested in, I'll edit this answer later for a possible strategy for those.

• I think this should do the trick, thanks. – mcandril Jun 4 '12 at 11:50
• Why don't you write just simply Limit[TriangleWave'[1/4 + eps], eps -> 0, Direction -> #] & /@ {1, -1} returning {4, -4} ? – Artes Jun 4 '12 at 15:23
• @Artes: I didn't want to have to evaluate TriangleWave'`? Besides, I wanted OP to see that the textbook definition is usable here... – J. M. will be back soon Jun 4 '12 at 15:28