1
$\begingroup$

I am experiencing unexpected behavior from Plot and D, and I would like to understand why. If I try this:

Plot[D[x,x],{x,1,10}]

I get a General::ivar error, but if I do this:

f = D[x,x]

Plot[f,{x,1,10}]

it works just fine. I come from a Python/Julia background, so I find this behavior baffling. What is going on here?

$\endgroup$
  • 2
    $\begingroup$ Plot holds its arguments and evaluates them once numerical values have been substituted for the variable, so you end up evaluating D[some number, some number], which of course does not make sense. You need to force pre-evaluation of D, which is exactly what you achieve when you define f. You would obtain the same result with Plot[Evaluate@D[x, x], {x, 1, 10}]. Take a look at Evaluation of Expressions and in particular the part about non-standard evaluation. $\endgroup$ – MarcoB Apr 30 at 19:44
  • $\begingroup$ Also, please note that D is a built-in function so you should probably choose another name. $\endgroup$ – anderstood Apr 30 at 19:50
  • $\begingroup$ @anderstood Yes, I was using D as the built-in derivative function. The example I gave of differentiating $x$ is just to illustrate the problem. $\endgroup$ – Yly Apr 30 at 20:22
  • $\begingroup$ @MarcoB Thanks, that answers my question. I would accept that as an answer if you are interested in writing it as one. $\endgroup$ – Yly Apr 30 at 20:23
  • $\begingroup$ I added the message name so that if you search, say, for "ivar Plotting", you would find an answer to your question. $\endgroup$ – Michael E2 Apr 30 at 20:47