I've looked to the built-in help of Mathematica, but I still can't understand the usage of /., like in the following expression:

mytangent[f_, x_, p_] := (f'[x] /. x -> p) (x - p) + f[p]

If /. just means that p replaces x, why don't write directly f'[p], etc?

  • 1
    $\begingroup$ There are many cases where you have to use ReplaceAll which is what /. is shorthand for. In this case you can use f'[t] easily though $\endgroup$ – Jason B. Apr 22 '16 at 11:39
  • $\begingroup$ Evaluate this: ?/. in Mma and you will see the hint. $\endgroup$ – Alexei Boulbitch Apr 22 '16 at 12:00

To be very explicit and related to the situation in your question, consider this simple function f and the different fs that all might be ways to compute the derivative at a first glance.

ClearAll[f, fs, fs2, fs3, fs4];
f[x_] := x^2;
fs[x_] := D[f[x], x];
fs2[x_] := f'[x];
fs3[x_] = D[f[x], x];
fs4[x_] := Block[{t}, D[f[t], t] /. t -> x];

Let's check what happens if we want to know the derivative at x=3.


General::ivar: 3 is not a valid variable. >> fs2[3] (* 6 ) fs3[3] ( 6 ) fs4[3] ( 6 *)

So we observe, everything except fs works well. But what is wrong with fs? Let us have a look at this:

(* {fs[3],D[f[3],3],{f[3],3^2,9},D[9,3],...} *)

What happens is that Mathematica wants to take the derivative of the value f[3] which is 9 with respect to its argument 3. Clearly, this doesn't make any sense, so there's the General::ivar error.

A "fix" is to use any of the three other approaches:

  • fs2 is how you have it in your question. Mathematica takes care of the order of evaluation internally, so here no need to use ReplaceAll, as mentioned in the comments. You can also inspect Trace[fs2[3]] to see why.
  • fs3 uses Set instead of SetDelayed in contrast to fs. This means, it evaluates the derivative once, and then just plugs in values for x.
  • fs4 demonstrates how you can use ReplaceAll in order to obtain the derivative via a SetDelayed definition and using a form like in fs. Here, you take the derivative w.r.t. the local symbol t (hence the Block) and then afterwards insert the value of interest using /..

As a sidenode, fs3 evaluates roughly an order of magnitude faster than the others since it has already computed the derivative and only needs to compute its value at the given position.


See ReplaceAll and What are the most common pitfalls awaiting new users?.

Say you want to find a root, you would code something like

rule = FindRoot[x^3 - Tanh[x], {x, 1.0, 1.2}]

and get as result:

{x -> 0.893395}

Next step ist (as proposed by @Alexei Boulbitch)

expr/.rules applies a rule or list of rules in an attempt to transform each subpart of an expression expr.  >>

soln = x /. rule


And use it like so:

Plot[x^3 - Tanh[x], {x, 0, 1}, Epilog -> {Red, PointSize[Large], Point@{soln, 0}}]

enter image description here


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