(*********************************************************************

	Copyright 1989 by Roman E. Maeder
	
	Adapted from
	Roman E. Maeder: Programming in Mathematica, Addison-Wesley, 1989.

	Permission is hereby granted to make copies of this file for
	any purpose other than direct profit, or as part of a
	commercial product, provided this copyright notice is left
	intact.  Sale, other than for the cost of media, is prohibited.
	
	Permission is hereby granted to reproduce part or all of
	this file, provided that the source is acknowledged.

 *********************************************************************)


BeginPackage["RMPackages`Newton`"]

NewtonZero::usage = "NewtonZero[expr, x, x0] finds a zero of expr as a function of x
	using the initial guess x0 to start the iteration. NewtonZero[f, x0] finds
	a zero of the function f. The recursion limit determines the
	maximum number of iteration steps that are performed."

NewtonFixedPoint::usage = "NewtonFixedPoint[f, x0] finds a fixed point
	of the function f using the initial guess x0 to start the iteration."

Newton::noconv = "Iteration did not converge in `1` steps."

Begin["`Private`"]

NewtonZero[expr_, x_, x0_] := NewtonZero[ Function[x, expr], x0 ]

NewtonZero[f_, x0_] :=
	Block[{res, x0a, prec = Precision[x0], fp = f'},
		x0a = SetPrecision[x0, prec + 10];
		res = FixedPoint[(# - f[#]/fp[#])&, x0a, $RecursionLimit];
		x0a = f[res];
		If [ Accuracy[x0a] - Precision[x0a] < prec,
			Message[Newton::noconv, $RecursionLimit] ];
		N[res, prec]
	]

NewtonFixedPoint[f_, x0_] := NewtonZero[(f[#] - #)&, x0]

End[]

Protect[ NewtonZero, NewtonFixedPoint]

EndPackage[]
