evaluation - General::ivar is not a valid variable when plotting - what actually causes this and how to avoid it?
I was just evaluating a couple of expressions and started to get errors like this:
General::ivar: -1.49994 is not a valid variable. >>
General::ivar: -1.43871 is not a valid variable. >>
General::ivar: -1.37749 is not a valid variable. >>
General::stop: Further output of General::ivar will be
suppressed during this calculation. >>
I'm doing nothing complicated - currently, I simply did this:
f[x_]:=x^2 + 2x + 1
Plot[f[x], {x, -4, 4}]
Solve[f[x] == 4]
g[x_]:=D[f[x], x]
Plot[g[x], {x, -2, 2}]
// ^ errors caused by this
Actually, this isn't the exact quadratic I am investigating, but it is a quadratic and I expected this to work. I googled, as you'd expect, and found this Stack Overflow question which suggested:
Plot[Evaluate[g[x]], {x, -2, 2}]
As a workaround.
It works - my question is, why doesn't that set of instructions generate that error (I can see it is something to do with replacing, but why is one plot different from the other?) and how can I avoid it? Is there something I should specifically have done in forming g
?
Answer
The problem lies in g[x_] := D[f[x], x]
; remember that what SetDelayed
(that is, :=
) does is to replace stuff on the right corresponding to patterns on the left before evaluating. Thus, when one does something like g[2]
(and something like this happens within Plot[]
), you are in fact evaluating D[f[2], 2]
, and since one cannot differentiate with respect to a constant ;), you get the General::ivar
error message.
If you use Set
instead (that is, g[x_] = D[f[x], x]
), f[x]
is differentiated first before the result of D[]
is assigned to g[x_]
. Since what's on the right of g[x_]
is now an actual function, Plot[]
no longer has a reason to complain.
Comments
Post a Comment