# f'[x] not the same as D[f[x],x]?! (Problems with Plotting..) [duplicate]

I have a very strange problem I'm sure I haven't had before, but I'm new to Mathematica, so maybe I'm just tired and can't see the obvious.

The Problem is, that for some reason Plot[] won't work with D[f[x],x], although it accepts f'[x]:

f[x_] := x^2

Plot[f'[x], {x, 0, 1}]
Plot[D[f[x], x], {x, 0, 1}]


The first command plots just fine, the second one gives several error messages "General::ivar: 0.000020428571428571424 is not a valid variable." with different numbers.

But they should be the exact same expression? I checked with SameQ[]:

In:= f'[x] === D[f[x], x]
Out= True


And this works:

Plot[D[f[a], a] /. a -> x, {x, 0, 1}]


But I don't think that's how Mathematica is supposed to be used..

Can someone help?

(Also I'm not sure about the tags, this probably hasn't anything to do with plotting - feel free to change them!)

• Plot[Evaluate@D[f[x], x], {x, 0, 1}] works. – bbgodfrey Apr 4 '17 at 1:28
• @bbgodfrey oh, so Plot doesn't evaluate the argument first.. I just found this in the help: "In some cases, it may be more efficient to use Evaluate to evaluate f symbolically before specific numerical values are assigned to x" – Bleagle Apr 4 '17 at 1:35
• Precisely so. In this case, Evaluate keeps D[f[x], x] from turning into D[f[0], 0]. Even if that were not an issue, Evaluate would reduce runtime. – bbgodfrey Apr 4 '17 at 1:38

As David said, Plot[D[f[x], x], {x, 0, 1}] tries to evaluate D[f[0], 0].

Your problem is all about the order of evaluation. Plot substitutes constants in for x BEFORE the D[f[x], x] is evaluated. Instead, use:

Plot[Evaluate[D[f[x], x]], {x, 0, 1}]

• Yes, bbgodfrey commented the same thing, I will accept this answer - thanks! Order of Evaluation was my problem. One quick question then: Why does SameQ still output true then? – Bleagle Apr 4 '17 at 1:44
• SameQ will output to true because both are the same as 2x. SameQ will evaluate both expressions, then say they are equal. If you put both Plot statements in your question into SameQ, it will throw an error, because of the D[f[0],0], but if you wrap D[f[x],x] in Evaluate[], then SameQ will say that they are equal. I hope that makes sense. – J.P. Apr 4 '17 at 1:56
• I see, it's all just about Evaluation ^^ – Bleagle Apr 4 '17 at 2:02
• @Bleagle. It is about Plot not doing standard evaluation of its arguments because it has the attribute HoldAll. – m_goldberg Apr 4 '17 at 14:57
• @m_goldberg: Ah, that's good to know - thanks! – Bleagle Apr 5 '17 at 22:09

In

Plot[D[f[x], x], {x, 0, 1}]

the code treats x as a variable whose value changes between 0 and 1. It makes no sense to plot D[f[0],0] (for instance), because f[0] is a constant. Likewise for every other value of x.

In contrast, f'[x] is a function evaluated at different values of x`.

• I thought about that, too, but they're the same expression, aren't they? I thought D[] would be evaluated first, then Plot. – Bleagle Apr 4 '17 at 1:32