Approaching function roots using the Newton method in OCaml

Hello,

Here is some OCaml code I’ve written that let me approach function roots using the Newton method.

You don’t know or don’t remember what it is and how it works ? Check the Wikipedia article about Newton’s method.

So here we just define iteration criterias and then, until we’re satisfied, calculate x_{n+1} = x_{n} - \frac{f(x_{n})}{f'(x_{n})} at each loop cycle. deriv and loop are very helpful functions that are used in approx_newton.

1
2
3
4
5
6
7
8
9
10
11
let deriv (f,dx) x = (f(x +. dx) -. f(x)) /. dx;;
 
let rec loop p f x = 
	if(p x) then x 
	else loop p f (f x);;
 
let approx_newton (f,start,dx,epsilon) =
  	let ok x = abs_float(f x) < epsilon in
  	let get_closer x = let f' = deriv(f,dx) in
  		(x -. f x /. f' x) in
  		loop ok get_closer start;;

dx and epsilon are precision factors… More little they are, better it is.
start shouldn’t be far from the searched root.
f is a function.

Now, let’s take a look at an approx_newton call.

First, our functions’ types :

# #use “C:/Program Files/Objective Caml/alp/maths.ml”;;
val deriv : (float -> float) * float -> float -> float =
val loop : (’a -> bool) -> (’a -> ‘a) -> ‘a -> ‘a =
val approx_newton : (float -> float) * float * float * float -> float =

And now the call and the result.

# approx_newton ((fun x -> cos(x /. 2.)), 3.1, 1e-15, 1e-15);;
- : float = 3.1415926535897949

Here, I want to obtain a root of the f : x \rightarrow cos(\frac{x}{2}) function that is near of 3.1 with precision factors of 10^{-15}.

Of course, you’ve understood we’re approaching pi.

Be careful : as said on Wikipedia, you should give, if possible, a close start point.