# Strange behavior of derivative when using Abs[] [duplicate]

This code where I try to visualize Newton's Method on the function $f(x)=\sqrt{|x|}$ works fine when I define $f(x)$ piecewise. Then why doesn't it work when I define f[x_] = Sqrt[Abs[x]]?

This works:

Clear["Global*"];
f[x_] = Piecewise[{{Sqrt[x], x >= 0}, {Sqrt[-x], x < 0}}];
guess = 5;
iter = 10;
xn = NestList[# - f[#]/f'[#] &, guess, iter] // N;
fn = f /@ xn;
dots = Transpose[{xn, fn}] /. {x_, y_} :> Sequence[{x, 0}, {x, y}];
Show[Plot[f[x], {x, -5, 5}], Graphics[Line[dots]]]


This doesn't work:

Clear["Global*"];
f[x_] = Sqrt[Abs[x]];
guess = 5;
iter = 10;
xn = NestList[# - f[#]/f'[#] &, guess, iter] // N;
fn = f /@ xn;
dots = Transpose[{xn, fn}] /. {x_, y_} :> Sequence[{x, 0}, {x, y}];
Show[Plot[f[x], {x, -5, 5}], Graphics[Line[dots]]]


But why???

• Do you know that |x| is not differentiable at x = 0? – Sascha Jul 12 '16 at 21:39

f[x_] = Piecewise[{{Sqrt[x], x >= 0}, {Sqrt[-x], x < 0}}];
f'[x]


gives

$$\begin{cases} -\frac{1}{2 \sqrt{-x}} & x<0 \\ \frac{1}{2 \sqrt{x}} & x>0 \\ \text{Indeterminate} & \text{True} \end{cases}$$

f[x_] = Sqrt[Abs[x]];
f'[x]


gives

$$\frac{\text{Abs}'(x)}{2 \sqrt{\text{Abs}(x)}}$$

So the second form doesn't evaluate the derivative in the way you think - it just substitutes e.g. Abs'[guess] but doesn't evaluate what that derivative is any further, and so gets stuck in a long loop.