While answering another question, I stumbled upon a problem I cannot easily resolve.
To assign the derivative of a function to another function, typically one can do this with a Set
or a SetDelayed
:
f[x_]=D[Sin[x],x]
f2[x_]:=Evaluate@D[Sin[x],x]
Both give the same result, since forcing evaluating on a SetDelayed
is essentially the same as using Set
. However, both can give rise to naming conflicts, i.e.
x=7;
f[x_]=D[Sin[x],x]
f2[x_]:=Evaluate@D[Sin[x],x]
won't work. This bothers me a lot, because the reason I always use SetDelayed
is to avoid this (sometimes difficult to find) type of bugs. So I tried to force some kind of local scoping, but until now didn't find a working solution. Using
f3[x_]:=Evaluate[Block[{x},D[Sin[x],x]]]
f4[x_]:=Evaluate[Module[{x},D[Sin[x],x]]]
f5[x_]:=Evaluate[With[{y=x},D[Sin[y],y]]]
doesn't work, because Block
and With
release the variable too fast and Module
renames it locally (as can be seen by doing ?f3
, ?f4
or ?f5
).
What does work, is using
f6[x_] := With[{y = x}, Evaluate@D[Sin[y], y] /. y -> x]
And it works even when both x
and y
already have an assigned value. However, if we look at its definition, we get:
?f6
Global`f6
f6[x_]:=With[{y=x},Evaluate[D[Sin[y],y]]/. y->x]
This is not what I want, because now the evaluation is delayed. Whenever my original function (here Sin[x]
) is much more complicated, the derivation can take some time. If I need to calculate a lot of values of f6
, this will stack up to a huge amount of time.
Any ideas to get a 'name-conflict-safe' derivative assignment which evaluates at its definition?
Derivative
instead ofD
, e.g.f[x_] := Derivative[1][Sin][x]
. See e.g. this answer mathematica.stackexchange.com/questions/5434/… $\endgroup$Derivative
(see my answer), I think your example doesn't pre-evaluate the symbolic derivative which I think is what the OP is trying to achieve. $\endgroup$