5
$\begingroup$

In this demonstration I'm working on, I would like to plot a piecewise function with the tangent line to the function at a point that is determined by c in the code below.

f[x_] = Piecewise[{{-x, x < 0}, {x^2, x >= 0}}];
g[x_] = Piecewise[{{-1, x < 0}, {2 x, x > 0}}];
Manipulate[
  Plot[{f[x], f[c] + g[c] (x - c)}, {x, -3, 3}, Epilog -> Point[{c,f[c]}]],
{c, Range[-2, 2, .025], ControlType -> Slider}]

Is there some way to restrict the increment c so that when it's negative, the increment size is the default size, whereas when it's positive, the increment size is something a bit smaller? I'm trying to make it easier to see that the derivative from the right approaches $0$. I'm not sure how to properly use an If command to this end.

$\endgroup$
2
  • 2
    $\begingroup$ You can join two ranges together: Join[Range[-2, 0, 0.025],Range[0.01, 2, 0.01]]. But you can't use If. $\endgroup$
    – C. E.
    Jun 29, 2015 at 1:38
  • $\begingroup$ @Pickett Thanks for the tip, I had a feeling I was being too hopeful :) $\endgroup$
    – user170231
    Jun 29, 2015 at 1:54

2 Answers 2

6
$\begingroup$

You can do this: Modify the If statement in the second argument of dynamics as you like. I set it now to jump by 0.2 if c<0 and jump by 0.01 if c>0 but you can change this.

f[x_] = Piecewise[{{-x, x < 0}, {x^2, x >= 0}}];
g[x_] = Piecewise[{{-1, x < 0}, {2 x, x > 0}}];
Manipulate[
 Plot[{f[x], f[c] + g[c] (x - c)}, {x, -3, 3},
  Epilog -> Point[{c, f[c]}], ImagePadding -> 10, PlotRange -> {-3, 3}
  ],
 Grid[{{Manipulator[
     Dynamic[c, {c = #; If[c < 0, incr = 0.2, incr = 0.01]} &],
     {-2, 2, Dynamic@incr}, ImageSize -> Tiny], Dynamic[c]}}],

 {{c, .1}, None},
 {{incr, .025}, None}
 ]

enter image description here

$\endgroup$
1
  • $\begingroup$ Your code might get simplified by replacing the Grid part with something like Row[{Slider[Dynamic@c, {-2, 2, Dynamic@If[Dynamic@c < 0, 0.2, 0.01]}, Appearance -> "Labeled"]}]. This avoids introducing incr as another variable and having a Function as the second argument of Dynamic. $\endgroup$
    – Karsten7
    Jun 29, 2015 at 15:03
2
$\begingroup$

One can make c and a stepsize with an If statement interdependent controls of the Manipulate without showing stepsize. However, this only works after making the If statement Dynamic.

f[x_] = Piecewise[{{-x, x < 0}, {x^2, x >= 0}}];
g[x_] = Piecewise[{{-1, x < 0}, {2 x, x > 0}}];

Manipulate[
 Plot[{f[x], f[c] + g[c] (x - c)}, {x, -3, 3}, Epilog -> Point[{c, f[c]}]], 
 {{stepsize, Dynamic@If[c < 0, .2, .01]}, None}, 
 {c, -2, 2, stepsize, ControlType -> Slider, Appearance -> "Labeled"}]

Output

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.