leibniz/examples/numerical.ml
2026-01-19 03:37:26 +00:00

26 lines
880 B
OCaml

open Leibniz
let () =
print_endline "root finding\n";
let f = Parser.parse "x^2 - 4" in
print_endline ("finding roots of f(x) = " ^ Expr.to_string f);
(match Numerical.bisection f "x" 0.0 3.0 0.0001 100 with
| Some root -> Printf.printf "bisection: root ≈ %.6f\n" root
| None -> print_endline "bisection failed");
(match Numerical.newton_raphson f "x" 1.0 0.0001 100 with
| Some root -> Printf.printf "newton-raphson: root ≈ %.6f\n" root
| None -> print_endline "newton-raphson failed");
print_endline "\nnumerical integration\n";
let g = Parser.parse "sin(x)" in
print_endline ("integrating g(x) = " ^ Expr.to_string g);
let trap = Numerical.trapezoidal g "x" 0.0 3.14159265 100 in
Printf.printf "trapezoidal rule: %.6f\n" trap;
let simp = Numerical.simpsons g "x" 0.0 3.14159265 100 in
Printf.printf "simpson's rule: %.6f\n" simp