Two more ways:
der[x_] := f'[x];
der[x_] := With[{df = D[f[#], #]}, df &[x]];
The second way follows the way the system implements f'
(Derivative
), so they're as safe as Mathematica.
However, both solutions above suffer the same restriction that Derivative
does:
This is okay:
ff[x_] := Sin[3 * x];
der[x_] := ff'[x];
der[x]
(* 3 Cos[3 x] *)
But not this:
ff[x_] := Sin[# * x];
der[x_] := ff'[x];
der[x]
(* 2 x Cos[x^2] *)
What happened to the coefficient #
??? (For a hint, use Trace
.)
You can check directly that ff'[x]
misbehaves:
ff'[x]
D[ff[x], x]
(*
2 x Cos[x^2]
Cos[x #1] #1
*)
Moral: Slot[]
is not safe as a parameter when differentiating.
Set
rather thanSetDelayed
:der[x_] = D[f[x], x]
or useEvaluate
:der[x_] := Evaluate@D[f[x], x]
. In either case, afterwards look at?der
$\endgroup$Sin[u]
changeder
toder[u_, x_] := D[f[u], x]
, allowing you to callder[x^2, x]
$\endgroup$