Message Boards Message Boards

0
|
126 Views
|
4 Replies
|
5 Total Likes
View groups...
Share
Share this post:

Why is Evaluate[ ] needed for D[ ] inside Plot[ ]?

Why do I need the Evaluate[] in the code below?

cdf = CDF[NormalDistribution[0, 1], x]
Plot[D[cdf, x], {x, -3, 3}] (* Doesn't work *)
Plot[Evaluate[D[cdf, x]], {x, -3, 3}]  (* Works *)
POSTED BY: Jay Gourley
4 Replies

I suppose one might take the question to mean, Why was it decided to have Plot[] hold its arguments and not evaluate the function(s) until the variable has been given a value? It is a choice. If Plot[] (and Table[], etc.) let their arguments be evaluated, then we would have to learn to program our plotting as follows, unless we could be sure x had not already been given a value:

Block[{x},
 Plot[D[Sin[x], x], {x, 0, 10}]
 ]

Programmers could Block[] the variables themselves instead of having Plot[], Table[], etc. do it automatically. We would get used to it, and maybe someone would be asking, Why do I have to use Block[]?

Instead another choice was made, and occasionally we have to use Evaluate[]. As Gianluca said, Mathematica programmers have to get used to this. The number of times I have to use Evaluate[] is fairly small compared to how often I would have to use Block[], so the choice seems convenient to me. OTOH, I was used to having to localize variables in C, so having to use Block[] all the time would probably have seemed normal.

POSTED BY: Michael Rogers

One more explanation:

Plot has the attribute HoldAll - for good reasons! Just mimic of not having this attirbute (and try):

x = 3;
Plot[Evaluate@Sin[x], {x, 0, 2 Pi}]
POSTED BY: Henrik Schachner

Mathematica users must get used to this. Plot gives a numerical value to x before it evaluates the derivative, resulting in something like (d f(1)) / (d1) from (d f(x)) / (dx). Evaluate forces the symbolic calculation of the derivatives before the numerical values come in. Also compare

Plot[RandomReal[], {x, 0, 1}]
Plot[Evaluate[RandomReal[]], {x, 0, 1}]
POSTED BY: Gianluca Gorni
Posted 1 day ago

Plot can be thought of as an extended Table, with the difference that Plot gives a graphical output.

Testing your example with Table gives some insight from the error messages and in the output:

POSTED BY: Hans Milton
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract