# Newton's Method

Problem statement:

I'm currently new to Mathematica and have been trying to solve this problem. I was digging around and found this code:

newtonmethod[error_, initial_, maxiteration_, errorpower_] :=
Module[{},
g[x_] := D[f[x], x];
h[t_] := t - f[t]/g[t];
guess = initial;
tol = error;
errorset = {};
ratios = {};
Do[
p = h[t] /. t -> guess;
tol = Abs[p - guess];
AppendTo[errorset, tol];
Print["n = ", n, ", x= ", N[ p], ", error =", N[ tol]];
guess = p;
If[tol <= error ∨ Chop[g[t] /. t -> guess] == 0,
Goto["errorcalculation"]],
{n, 1, maxiteration}];
Label["errorcalculation"];
Do[
AppendTo[ratios, errorset[[i + 1]]/errorset[[i]]^errorpower],
{i, 1, Length[errorset] - 1}];
Print["Here are the error ratios \n"];
TableForm[N[ratios]]]


I'm not really sure on how to use it and/or if it's enough to complete the problem. Any help would be greatly appreciated.

• Define the function for which a zero is desired, for instance, f[x_] := (x - 1)^2. Then, execute newtonmethod, for instance, newtonmethod[.0001, .1, 20, 2]. – bbgodfrey Sep 30 '18 at 5:15
• For your own benefit (be better at using Mathematica), try to do either (1) write your own code, or (2) understand the code; then you ask when you're stuck with doing one of the above. – user202729 Sep 30 '18 at 15:15
• Related/duplicate: (19655), (59877) – Michael E2 Sep 30 '18 at 15:26
• @bbgodfrey I defined my function and then tried to execute newtonmethod and received no output – JVang10 Sep 30 '18 at 18:32
• Did you enter and execute the code for newtonmethod  first? – bbgodfrey Sep 30 '18 at 18:45

I offer an implementation more of Mathematica's style, I suppose,

Clear[findRootByNewton]
findRootByNewton[f : _Symbol | _Function, initPt_Real, η_:1.*^-6] := Module[{df},
df = Derivative[1][func];
NestWhileList[# - f[#]/df[#] &, initPt, Abs[Subtract[##]] >= η &, 2]
]


One needs to provide the function (of pure function form or defined by SetDelayed (:=)) whose root to be found, the initial guess and an optional precision goal with a default value of $$1.0\times 10^{-6}$$.

Then I use $$f(x)=x^2-2$$ as an example. Either

findRootByNewton[#^2 - 2 &, 1.]


or

f[x_] := x^2 - 2
findRootByNewton[f, 1.]


returns

{1., 1.5, 1.41667, 1.41422, 1.41421, 1.41421}


The result shows root approximations found at each iteration, until the preset precision goal is reached.

P.S.

If one just wants the final result, use NestWhile instead of NestWhileList.

• When trying your code I get an output of the following: {1., 1.+1./func'[1.]} I can't seem to figure out why it's providing me the exact result and not the decimal approximation. – JVang10 Sep 30 '18 at 17:27
• @JVang10 What is your $f(x)$, then? – Αλέξανδρος Ζεγγ Oct 1 '18 at 6:24