Newton's Method

Manipulate[
NewtonPlot[GetFunction[function],RangeToVary[GetRange[function],x0],10^(-2),GetRange[function],zoom,20],
{{function,functionrules[[1,1]]},Dynamic[First/@functionrules,SynchronousUpdating->False],ControlType->PopupMenu},
{{x0,0,"starting point"},0,1},
{{zoom,0.9},0.1,.9},
TrackedSymbols:>{function,x0,zoom},
SynchronousInitialization->False,
AutorunSequencing->{2,3},
Initialization:>(
NewtonsMethod[f_,x_, nz_ : 10^(-10)]:=If[Abs[f'[x]] > nz ,N[x - ((f[x])/(f'[x]))],NewtonError];
ConvergenceTest[f_,x_,tol_]:=(Abs[x] > tol &&  x =!= NewtonError);
FindRootNewton[f_,x0_,tol_, maxiter_:100]:=NestWhileList[NewtonsMethod[f,#]&,x0,ConvergenceTest[f,#,tol]&,1,maxiter];
pointStyle[size_,color_,pt_]:={PointSize[size],color,Point[pt]};
stdopts = Sequence[ImageSize->{250,150},PlotStyle->Black];
NewtonPlot[f_,x0_,tol_,{xmin_,xmax_},zoom_, max_]:=Module[{iterates = 
FindRootNewton[f,x0,tol,max],fmtpts,fmtlines,fmtarrows,ip,fp,lp},
lp = Last[iterates];
If[lp =!= NewtonError,
fp  = pointStyle[Large,Red,{#,f[#]}&@ Last[iterates]];
ip = pointStyle[Large,Green,{#,f[#]}]&@ First[iterates];
fmtpts = pointStyle[Medium,Blue,{#,f[#]}]&/@iterates;
fmtlines ={ {Blue,Line[{{First[#],f[First[#]]},{Last[#],0}}]},{Orange,Line[{{Last[#],0},{Last[#],f[Last[#]]}}]}}&/@Reverse[Partition[iterates,2,1]];
Grid[{{Plot[f[x],{x,xmin,xmax},Epilog-> {fmtlines,fmtpts,ip,fp},Evaluate[stdopts]],Plot[f[x],{x,lp - zoom,lp+zoom},Epilog-> {fmtlines,fmtpts,ip,fp},Evaluate[stdopts]]},
{Plot[f[x],{x,lp - zoom^2,lp+zoom^2},Epilog-> {fmtlines,fmtpts,ip,fp},Evaluate[stdopts]],Plot[f[x],{x,lp - zoom^3,lp+zoom^3},Epilog-> {fmtlines,fmtpts,ip,fp},Evaluate[stdopts]]}} ],
"Newton Error Divide by Zero"]
];
functions = {
{Function[x,3 Cos[x] + Sin[x]],{-2,2.5},1},
{Function[x,Exp[x] - x^2],{-2,2},1},
{Function[x,x^2 -1],{-2,2},0},
{Function[x,Cos[x] - x^4],{-2,2},1},
{Function[x,Cos[9 x] + 5x - 2],{-2,2},1},
{Function[x,Sin[12 x] - x^2 +3],{-1,2},2}
};

functionrules = ToString[Last[First[#]],TraditionalForm]-> #&/@ functions;
GetFunction[str_]:=First[str /. functionrules];
GetRange[str_]:=Part[str/.functionrules,2];
RangeToVary[{a_,b_},x_]:=a + x(b-a);
)]

CAPTION

Explore Newton's method of root finding for several functions. Use the zoom slider to see more detail at three different levels of zoom.

THIS NOTEBOOK IS THE SOURCE CODE FROM

"Newton's Method" from the Wolfram Demonstrations Project
 http://demonstrations.wolfram.com/NewtonsMethod/

Contributed by: Chris Maes

A full-function Wolfram Mathematica system (Version 6 or higher) is required to edit this notebook.
GET WOLFRAM MATHEMATICA »

© Wolfram Demonstrations Project & Contributors   |   Terms of Use   |   Make a new version of this Demonstration »