Scoping in assigning a derivative
This might work as you expect and be save even if definitions for x
exist:
Block[{x}, f[x_] = D[Sin[x], x];]
I would strongly suggest that you get familiar with Derivative
and pure functions if you work with symbolic derivatives, though. This will make your life much easier in the long term. Your example would reduce to:
f = Derivative[1][Sin]
and a more complicated example would also work, e.g.:
f = Derivative[1][Exp[# - Sin[#]] &]
or even:
g[x_] := Exp[x^2 + Sin[x]];
gprime = Derivative[1][g]
You could use Formal Symbols:
f[\[FormalX]_] = D[Sin[\[FormalX]], \[FormalX]]
Which looks like this in the Notebook:
Formal Symbols are entered with Esc$x
Esc where x
is any regular letter.
Formal Symbols cannot be assigned a global value, avoiding collisions:
Set::wrsym: Symbol [FormalX] is Protected. >>
I also wrote a function localSet
to answer a prior question which you could use:
x = 1.23;
localSet[ f[x_], D[Sin[x],x] ]
DownValues[f]
{HoldPattern[f[x_]] :> Cos[x]}