Newton's Method for solving equations.

I've hidden a program for showing a single step of Newton's method here.  The program is called NewtonStep, and it requires as input the name of a function f,  and an initial guess for a root of f[x] = 0.

Needs["Graphics`Colors`"]
NewtonStep[f_,guess_]:=Module[{next,realroot,line,curve},next=guess-N[((f[guess])/(f'[guess]))];Print["guess =  ",guess,"   next  = ",next];realroot=next;scale=1.5` Abs[guess-realroot];line=Plot[f[guess]+f'[guess] (x-guess),{x,realroot-scale,realroot+scale},PlotStyle->{AbsoluteThickness[2],Red},DisplayFunction->Identity];curve=Plot[f[x],{x,realroot-scale,realroot+scale},PlotStyle->{AbsoluteThickness[2],Black},DisplayFunction->Identity];points=Graphics[{PointSize[0.02`],Blue,{Point[{guess,0}],Point[{guess,f[guess]}],Point[{next,0}]}},Color->Blue];Show[{line,curve,points},DisplayFunction->$DisplayFunction]]

Let's define a function to test the single step Newton's method.

Clear[f];
f[x_]:=(x^3)-6 x+1; Plot[f[x],{x,-3,3}]

Let's try to find the root of f[x] = 0 which is between 2 and 3, by using the initial guess  x = 3.

NewtonStep[f, 3]

Try it again, taking the "next" value of x from the previous step as our new "guess".

NewtonStep[f, 2.52381]

And again.

NewtonStep[f, 2.37636]

And again.

NewtonStep[f, 2.36161]

NewtonStep[f, 2.36147]

Here is a Newton's method program, which repeats the basic step until the difference between the current guess and the next value of x is very small, and then stops.  (We will discuss a flowchart for the program in class.)

Clear[NaiveNewton]
Off[General::spell1]
NaiveNewton[f_,guess_]:=
	Module[{newtstep,root},
		newtstep=1;
		root=guess;
		While[Abs[newtstep]>10^(-6),
			newtstep=N[-((f[root])/(f'[root]))];
			root=root+newtstep;
		Print[root];
		];
		N[root,6]]

Let's use our program to find the root of f[x] = 0 which lies between 2 and 3.

NaiveNewton[f,3]

There is a built-in Newton's method procedure in Mathematica,  called FindRoot.  Let's see that the built-in procedure gives the same result.

FindRoot[f[x], {x, 3}]

Let's use Newton's method to compute the square root of a number.

OurSqrt[a_] := Module[{f, guess},
		guess = a;
				f[x_] = x^2-a;
	NaiveNewton[f, guess]
	]

Example:  compute the square root of 2.

OurSqrt[2]

Here's a method of computing cube roots.

OurCubeRoot[a_] := Module[{f, guess},
		guess = a;
				f[x_] = x^3-a;
	NaiveNewton[f, guess]
	]

OurCubeRoot[.3]

Let' s solve the equation (e^x)=4 x

f[x_] := Exp[x] - 4x;
Plot[f[x], {x, 0, 3}]
Plot[{Exp[x], 4x}, {x, 0, 3}]

NaiveNewton[f, .5]
NaiveNewton[f, 2]