Newton Raphson

The Newton Raphson method is designed to make convergence as quick as possible.

Clear[f,x0,eps,nits];

This is the algorithm:

NewtonsMethod[f_,a0_,eps_,nits_] :=
Module[
{a=N[a0], (* Use a local variable (so as not to alter passed arguments) *)
fa = f[N[a0]],
i=0,
output (* Let's collect the output, since we've gone to the trouble of computing it. *)
},
output={{i,a,fa}}; 
While[Abs[fa] > eps && i<nits,
a = a-(fa/(f'[a]));
fa=f[a];
i=i+1;
output=Append[output,{i,a,fa}];  (* once again, collect output. *)
]; 
(* Now let's augment the naive function to include printing some nice formatted output: *)
Print[NumberForm[TableForm[output,
TableHeadings->{None,{"i","(Subscript[x, k])","f[(Subscript[x, k])]"}}],16]]; 
Print["  x  = ",NumberForm[a,16] ]; 
Print["f(x) = ",NumberForm[fa,16] ]; 
Return[Transpose[output]]; (* Now I'll actually return the output, so that it can be plotted, etc. *)
]

This is an example which reduces to the Babylonian square root algorithm:

This one converges to a root for any starting value (except for one -- can you tell which initial value of x will cause trouble?): do you see why, and how it will converge?

f[x_]=(x^2)-2;
Plot[f[x],{x,-2,2}]
x0=.2;
eps=10^(-6);
nits=100;
NewtonsMethod[f,x0,eps,nits];

Division -- without division! Well, it looks like there’s division -- but if you work out a = a-((f[a])/(f'[a])) it loses the quotient.

f[x_]=1/x-2;
Plot[f[x],{x,-2,2}]
x0=.2;
eps=10^(-6);
nits=10;
NewtonsMethod[f,x0,eps,nits];

But sometimes it doesn’t converge....

Once again, the starting value is very important:

x0=2;
NewtonsMethod[f,x0,eps,nits];