From 13fb1bd7a981dfd64bf92cccd33b5df71ffaa196 Mon Sep 17 00:00:00 2001 From: giles Date: Sat, 9 May 2026 08:29:01 +0000 Subject: [PATCH] ocaml: phase 5.1 newton_sqrt.ml baseline (Newton's method, sqrt(2)*1000 = 1414) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Newton's method for square root: let sqrt_newton x = let g = ref 1.0 in for _ = 1 to 20 do g := (!g +. x /. !g) /. 2.0 done; !g 20 iterations is more than enough to converge for x=2 — result is ~1.414213562. Multiplied by 1000 and int_of_float'd: 1414. First baseline exercising: - for _ = 1 to N do ... done (wildcard loop variable) - pure float arithmetic with +. /. - the int_of_float truncate-toward-zero fix from iter 117 38 baseline programs total. --- lib/ocaml/baseline/expected.json | 1 + lib/ocaml/baseline/newton_sqrt.ml | 10 ++++++++++ plans/ocaml-on-sx.md | 7 +++++++ 3 files changed, 18 insertions(+) create mode 100644 lib/ocaml/baseline/newton_sqrt.ml diff --git a/lib/ocaml/baseline/expected.json b/lib/ocaml/baseline/expected.json index 6a61cd43..a11b46ce 100644 --- a/lib/ocaml/baseline/expected.json +++ b/lib/ocaml/baseline/expected.json @@ -23,6 +23,7 @@ "memo_fib.ml": 75025, "merge_sort.ml": 44, "module_use.ml": 3, + "newton_sqrt.ml": 1414, "mutable_record.ml": 10, "option_match.ml": 5, "pi_leibniz.ml": 314, diff --git a/lib/ocaml/baseline/newton_sqrt.ml b/lib/ocaml/baseline/newton_sqrt.ml new file mode 100644 index 00000000..51f95773 --- /dev/null +++ b/lib/ocaml/baseline/newton_sqrt.ml @@ -0,0 +1,10 @@ +let sqrt_newton x = + let g = ref 1.0 in + for _ = 1 to 20 do + g := (!g +. x /. !g) /. 2.0 + done; + !g + +;; + +int_of_float (sqrt_newton 2.0 *. 1000.0) diff --git a/plans/ocaml-on-sx.md b/plans/ocaml-on-sx.md index 3e799773..f9651bcc 100644 --- a/plans/ocaml-on-sx.md +++ b/plans/ocaml-on-sx.md @@ -407,6 +407,13 @@ _Newest first._ binary search tree (`type 'a tree = Leaf | Node of 'a * 'a tree * 'a tree`) with insert + in-order traversal. Tests parametric ADT, recursive match, List.append, List.fold_left. +- 2026-05-09 Phase 5.1 — newton_sqrt.ml baseline (Newton's method + for sqrt, sqrt(2)*1000 truncated → 1414). 20 iterations of + `g := (g + x/g) / 2` converges to ~1.414213562 for x=2. Multiplied + by 1000 and int_of_float'd gives 1414. First baseline that + exercises `for _ = 1 to N do ... done` (wildcard loop variable), + pure float arithmetic with `+.` `/.`, and the `int_of_float` fix + from iteration 117. 38 baseline programs total. - 2026-05-09 Phase 5.1 — hanoi.ml baseline (Tower of Hanoi move count, n=10 → 1023). Classic doubly-recursive solution returning the number of moves: `hanoi n from to via = hanoi (n-1) from via