0

I am trying to calculate the square root of a number by Ocaml, this is my code :

let isclose x y =  abs_float(x -. y)<0.001;;
let average x y = (0.5*.x)+.(0.5*.y);;
let rec guess x y = if isclose y (x /. y) then y else guess x (average y x/.y);;
let sqr x = guess x 1.;;

then, typing

sqr 1.;;

gives 1 as expected, but typing

sqr 2.;;

lasts undefinitely. Can one help with my error (I tested the algo in Python and it works as expected). Thanks for help

volatile
  • 899
  • 10
  • 22

1 Answers1

2

You want this:

let rec guess x y =
    if isclose y (x /. y) then y else guess x (average y (x/.y))

Note the extra parentheses.

The meaning of

average y x /. y

is

(average y x) /. y

Whereas you want:

average y (x /. y)
Jeffrey Scofield
  • 65,646
  • 2
  • 72
  • 108