ocaml: phase 5.1 newton_sqrt.ml baseline (Newton's method, sqrt(2)*1000 = 1414)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 26s

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.
This commit is contained in:
2026-05-09 08:29:01 +00:00
parent 39f4c7a9a8
commit 13fb1bd7a9
3 changed files with 18 additions and 0 deletions

View File

@@ -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,

View File

@@ -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)