From my comment, with the OP's typo, which I did not notice, fixed:
findRoot[expr_ == val_, {var_, init_}, \[Epsilon]_] :=
Module[{xi = init,
fun = Function[var, Evaluate[expr - val]]},
While[Abs[fun[xi]] > \[Epsilon],
xi = N[xi - fun[xi]/fun'[xi]]];
{var -> xi}]
findRoot[x^2 == 2, {x, 1.}, 10^-8]
(* {x -> 1.41421} *)
If you want the variable var to be protected from evaluation inside findRoot, just as it is in FindRoot, you can do the following:
ClearAll[findRoot];
SetAttributes[findRoot, HoldAll];
findRoot[expr_ == val_, {var_, init_}, \[Epsilon]_] :=
Module[{xi = init,
fun = Function @@ Hold[var, expr - val]},
While[Abs[fun[xi]] > \[Epsilon],
xi = N[xi - fun[xi]/fun'[xi]]];
{var -> xi}];
Then the following finds the root, just like FindRoot, but just like FindRoot, x is evaluated after the solution is returned. This could be prevented by returning {HoldPattern[var] -> xi} instead of {var -> xi}, but FindRoot does not do it.
x = 2;
findRoot[x^2 == 2, {x, 1.}, 10^-8]
(* {2 -> 1.41421} *)
As @m_goldberg's answer shows, it's good to have one core routine and have all the interfaces call it. Here's another way but putting the core routine in an "internal" function:
ClearAll[findRoot, iFindRoot];
iFindRoot[fun_, dfun_, init_, \[Epsilon]_] := Module[{xi = init},
While[Abs[fun[xi]] > \[Epsilon],
xi = N[xi - fun[xi]/dfun[xi]]];
xi];
findRoot[fun : _Symbol | _Function, {var_,
init_?NumericQ}, \[Epsilon]_] :=
{var ->
iFindRoot[fun, fun', init, \[Epsilon]]};
findRoot[fun : _Symbol | _Function, {init_?
NumericQ}, \[Epsilon]_] :=
{iFindRoot[fun, fun',
init, \[Epsilon]]};
findRoot[expr_ == val_, {var_, init_?NumericQ}, \[Epsilon]_] :=
Module[{fun},
fun = Function[var, Evaluate[expr - val]];
{var -> iFindRoot[fun, fun', init, \[Epsilon]]}];
fun = Function[fvar, Evaluate[expr - val]]-- This technique used here and here – Michael E2 Mar 25 '19 at 02:25varshould replacefvarin your/my codes. AlsoNest(orFixedPoint) could be used instead ofWhile, if you haven't seen it. – Michael E2 Mar 25 '19 at 13:33