2
$\begingroup$

The following function is a piecewise function. It's easy to plot with option Exclusions->None but it's derivative is hard to evaluate:

f[x_] = Import["http://pastebin.com/raw/qCfdYTbd"];
Plot[f[x], {x, -5, 5}, Exclusions -> None]

enter image description here

Plot[f'[x], {x, -5, 5}, Exclusions -> None]

enter image description here

The following works well for the Plot, but introduces very small and large values so I'd like a better solution to compute $f'$.

fp[x_] = (f[x + 10^-6] - f[x])/10^-6
$\endgroup$
2
  • 2
    $\begingroup$ Maybe a better definition of f: f[x_] = Assuming[{-5 < x < 5}, Simplify[Import["pastebin.com/raw/qCfdYTbd"] ]]? $\endgroup$ Sep 5, 2016 at 18:05
  • $\begingroup$ @FredSimons Indeed, that's much better! $\endgroup$
    – anderstood
    Sep 5, 2016 at 18:16

2 Answers 2

4
$\begingroup$

The problem is that Derivative[1, 0][Mod][x, 1] does not evaluate symbolically, but it is evaluated numerically when plotted (see Symbolic derivatives are being calculated numerically and its duplicates for more about the numerical evaluation).

Plot[f'[x] /. Derivative[1, 0][Mod][x_, m_] :> 
   Piecewise[{{1, Mod[x, m] != 0}}, Indeterminate], {x, -5, 5}, 
 Evaluated -> True, Exclusions -> None]

Mathematica graphics

It is important that the replacement rule is evaluated symbolically before plotting. I used Evaluate -> True, but you could use Plot[Evaluate[..], {x, -5, 5},..], save the derivative in a variable and then plot it, and so on.

$\endgroup$
2
$\begingroup$

Using Fred Simons simplification:

g[x_] = Assuming[{-5 < x < 5}, 
  Simplify[Import["http://pastebin.com/raw/qCfdYTbd"]]]; 
h[x_] = D[g[x], x];
Plot[h[x], {x, -5, 5}, PlotRange -> {-1, 1}]

enter image description here

Here h[x] is itself a nice piecewise function -- all the discontinuities evaluate to `Indeterminate' and so are not plotted.

$\endgroup$
2
  • $\begingroup$ Is there a reason why D[g[x],x] is better than g'[x]? $\endgroup$
    – anderstood
    Sep 5, 2016 at 19:01
  • $\begingroup$ It's just different ways of writing the same thing... $\endgroup$
    – bill s
    Sep 5, 2016 at 19:03

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.