(* file: bisection.ml author: Bob Muller CS1103 Computer Science I Honors Topics: - The Babylonian Bisection Algorithm for computing an approximation of the square root of a (possibly irrational) number. babylonianSqrt : float -> int -> float -> float *) let babylonianSqrt x n error = let closeEnough a b = abs_float (a -. b) < error in let rec repeat i lo hi = match i > n with | true -> failwith "unable to compute acceptable approximation" | false -> let middle = (lo +. hi) /. 2.0 in let midSquared = middle ** 2.0 in Printf.printf "attempt=%d: lo=%f, hi=%f, mid=%f\n" i lo hi middle ; match closeEnough midSquared x with | true -> middle | false -> (match midSquared < x with | true -> repeat (i + 1) middle hi | false -> repeat (i + 1) lo middle) in repeat 1 0.0 x (* The following version has a slightly more convenient interface. And it covers material not covered in lecture. In particular, the definition has default values for the number of iterations and the error. NB: the type. babylonianSqrt : ?n:int -> ?error:float -> float -> float *) let babylonianSqrt ?n:(n = 30) ?error:(error = 1e-6) x = let closeEnough a b = abs_float (a -. b) < error in let rec repeat i lo hi = match i > n with | true -> failwith "unable to compute acceptable approximation" | false -> let middle = (lo +. hi) /. 2.0 in let midSquared = middle ** 2.0 in Printf.printf "attempt=%d: lo=%f, hi=%f, mid=%f\n" i lo hi middle ; match closeEnough midSquared x with | true -> middle | false -> (match midSquared < x with | true -> repeat (i + 1) middle hi | false -> repeat (i + 1) lo middle) in repeat 1 0.0 x