I have the following example FindRoot function as part of a Nest function.
Clear[del]
del[x_] := Module[{y, dP, res, OP},
res := {y} /. FindRoot[y^2 + 2 y - x, {y, 0}];
OP := res[[1]];
dP := OP + 1;
Nest[(# + dP/#)/2 &, 1.5, 2]
]
del[name] /. name -> 3
Mathematica doesn’t recognise the “name” symbol and returns the following error:
"FindRoot::nlnum: The function value {0. -1. name} is not a list of numbers with dimensions {1} at {y$21486} = {0.}.
ReplaceAll::reps: {FindRoot[y$21486^2+2 y$21486-name,{y$21486,0}]} is neither a list of replacement rules nor a valid dispatch table, and so cannot be used for replacing."
If you set Nest to apply zero times or replace it with a function that doesn’t repeat the code works fine. It also works if you replace FindRoot with a simple assignment for symbol “OP”. However, it doesn’t work if you use Solve instead of FindRoot. Can anyone shine any light on this?
Many thanks Marco, much appreciated. Interestingly, if you use solve with the expression equated to zero it also works (in my original post I’d tried Solve without equating the expression to zero).
Clear[del]
del[x_] := Module[{y, dP, res, OP},
res := {y} /. Solve[y^2 + 2 y - x == 0, y];
OP := res[[1]];
dP := OP + 1;
Nest[(# + dP/#)/2 &, 1.5, 2]
]
del[name] /. name -> 3
Can’t figure out why this works and FindRoot doesn’t.
FindRoot attempts to find a root numerically. As you see the error message says that it fails to do so, because there is the variable y (with the $21486, because of the localisation of Module), and the variable: name. That cannot work. Solve uses other methods and in particular symbolic solutions which makes it work in this case (it doesn’t care that name is substituted later.
This is basically a combination of (i) when are the variables substituted by numbers and (ii) do you use symbolics or numerics, I would think.