Newton's Method

Maple has a break command to allow early exit of a program. Below we show a Newton's method for finding the zero of a function up to a prescribed tolerance.

> Newton := proc(f, x0, N, tol)

> local i, x1, x2, err, df:

> x1 := x0;

> df := unapply(diff(f(x),x),x);

> for i from 1 to N do

> x2 := x1 - f(x1)/df(x1);
err := evalf(abs(x2 - x1));

> if err < tol then

> print(`The zero of the function is x =`, x2, `in`, i, `iterations.`);

> break

> fi:

> x1 := x2;

> od:

> if i = N+1 then

> print(`The Newton method fails to converge in`, N, `iterations.`);

> fi:

> end:

We test this on a problem where we know a zero.

> f := x -> sin(0.5*x);

f := proc (x) options operator, arrow; sin(.5*x) en...

> x0 := 0.1: N := 3: tol := 1E-15:

> Newton(f, x0, N, tol);

`The Newton method fails to converge in`, 3, `itera...

> g := x -> sin(x) - x*cos(x);

g := proc (x) options operator, arrow; sin(x)-x*cos...

> x0 := 4.8: N := 10: tol := 1E-8:

> Newton(g, x0, N, tol);

`The zero of the function is x =`, 4.493409458, `in...

> plot(g(x),x=-10..10,y=-10..10);

[Maple Plot]