Mathematica issue with Plot, D and SetDelayed [duplicate]

I've tried to run the following code:

f[x_] := 2 ArcTan[x] + ArcSin[2 x/(1 + x^2)];
Plot[D[f[x], x], {x, -4, 4}]


Same with SetDelayed:

df[x_] := D[f[x], x];
Plot[df[x], {x, -4, 4}]


It starts to complaining:

General::ivar: -3.99984 is not a valid variable. >>
General::ivar: -3.83657 is not a valid variable. >>
General::ivar: -3.67331 is not a valid variable. >>
General::stop: Further output of General::ivar will be suppressed during this calculation. >>


But this code works:

f[x_] := 2 ArcTan[x] + ArcSin[2 x/(1 + x^2)];
df = D[f[x], x];
Plot[df, {x, -4, 4}]


Did I miss something or this is an issue?

• Why not do Plot[f'[x], {x, -4, 4}]? Commented Jun 8, 2013 at 7:22
• It's important to note why @0x4A4D's comment works and yours doesn't. The Plot command is passing in values to the function it is to plot. In the case of D[f[x],x] it is asking to take the derivative with respect to a numerical value, whereas f'[x] is asking for the derivative at a numerical value. Because the function isn't evaluated (unless you use Evaluate[]) this difference is important. Commented Jun 8, 2013 at 9:45

Plot needs to have Evaluate[ ] in order to have something to plot. So you can fix the error above by:

f[x_] := 2 ArcTan[x] + ArcSin[2 x/(1 + x^2)];
df[x_] := D[f[x], x];
Plot[Evaluate[df[x]], {x, -4, 4}]


If you look at the help file for Plot you can see that many of the functions plotted there need to be told explicitly to evaluate inside the plot command.

• It should be noted that this question is asked every month which strongly suggests there is something unnatural about how mathematica handles Plot. I realize there is some logic to it but... Commented Jun 8, 2013 at 10:15
• @chris I don't think Plot is the problem here (the "unnatural" logic makes complete sense). The real problem is that unlike other languages where you start getting familiar with the evaluation sequence early on in your learning, it comes very late in Mathematica — perhaps only after a few years of using it. A typical hello world is Plot[Sin[x], ... to show off the symbolic capabilities and it is only natural to want to try Plot[Table[Sin[k x]... but now you're stuck with 5 blue curves and you won't know why until you get deeper into language details such as attributes, evaluation, etc.
– rm -rf
Commented Jun 8, 2013 at 13:09