# Why is “1” not a valid variable? Why is there not a function plotted in the Plot function? [duplicate]

This is my code for playing this kind of stuff

    A = {1, 1};
B = {0, -1};
c = {x, 0};
l1 = EuclideanDistance[A, c];
l2 = EuclideanDistance[c, B];
f[x_] := l1/1 + l2/2;
D[f[x], x]
g[x_] := D[f[x], x]
g
Plot[g[x], {x, -20, 20}, PlotRange -> 20 {{-1, 1}, {-1, 1}},
PlotStyle -> Red, AspectRatio -> Automatic, ImageSize -> 400]


To clarify, there seem to be three or four questions, some of which are in the title, some to be inferred from comments or evaluating the code:

1. Why are Abs'[1 - x] and Abs'[x] left unevaluated in the output of D[f[x], x]?
2. Why does g result in an error "General::ivar 1 is not a valid variable"?
3. Why does Plot[...] generate similar General::ivar errors?
4. Why does the Plot comes up empty when only the previous two problems are fixed? (It came up blank originally because of the problem with D[...].)
• @MichaelE2, but your link hasn't answered the question about No Plot in the function – kile Oct 25 '19 at 2:19
• @MichaelE2, Thank u for your answer first, this link you put here hasn't answered the Plot problem in Abs. – kile Oct 25 '19 at 2:26
• Hi, I edited the questions you seemed to have about your code into the body of your post to make clear what all the questions are. I think the linked questions address each one, and it's nice to have the Q&A's linked because it helps others searching for answers to the same or similar problem. -- Also, here's another workaround: f[x_] = Block[{Abs = RealAbs}, l1/1 + l2/2] together with Carl's suggestion of g = f'. – Michael E2 Oct 25 '19 at 11:30

There are several things going on here. First, both l1 and l2 use Abs:

l1
l2


Sqrt[1 + Abs[1 - x]^2]

Sqrt[1 + Abs[x]^2]

Mathematica will not compute the derivative of Abs because it is not analytic as a complex function. One possibility is to use ComplexExpand to eliminate the Abs:

m1 = ComplexExpand @ l1
m2 = ComplexExpand @ l2


Sqrt[1 + (1 - x)^2]

Sqrt[1 + x^2]

Next, your definition of f is problematic because the RHS does not contain an explicit x variable. It is better to use either:

f[x_] = m1/2 + m2/2


or:

f[x_] := Evaluate[m1/2 + m2/2]


so that the RHS is evaluated when defining f. Finally, when you define:

g[x_] := D[f[x], x]


and evaluate g, Mathematica will try to evaluate:

D[f, 1]


which is why you get your message. It is much better to use:

g = f'


instead to define a derivative function. So:

Clear[f, g];

f[x_] = m1/2 + m2/2;
g = f';
Plot[g[x], {x, -20, 20}] • Carl Woll, thank you for your answer. What remained unanswered in this question was about how to add g in this code. How are you gonna solve this? – kile Oct 25 '19 at 2:22
• @kile Simply use g. Notice g[x_]=…… isn't the only way for defining a function, and in this case the function relationship g is defined by g=f'. – xzczd Oct 25 '19 at 5:54