symbolic mathematics engine in OCaml with differentiation, integration, simplification, and numerical methods
17

Configure Feed

Select the types of activity you want to include in your feed.

leibniz / examples / tier1.ml
1.8 kB 50 lines
1open Leibniz 2 3let () = 4 print_endline "polynomial expansion and collection\n"; 5 6 let expr = Parser.parse "(x + 1)^3" in 7 let expanded = Polynomial.expand expr in 8 print_endline ("expanded: " ^ Expr.to_string expanded); 9 10 print_endline "\ncommon subexpression elimination\n"; 11 12 let complex_expr = Parser.parse "sin(x + y) * cos(x + y) + sin(x + y)" in 13 let cse_result = Cse.common_subexpression_elimination complex_expr in 14 print_endline ("original: " ^ Expr.to_string complex_expr); 15 List.iter (fun (name, e) -> 16 print_endline (Printf.sprintf "%s = %s" name (Expr.to_string e)) 17 ) cse_result.subexpressions; 18 print_endline ("final: " ^ Expr.to_string cse_result.final_expr); 19 20 print_endline "\ncode generation to C\n"; 21 22 let f = Parser.parse "x^2 + sin(y) * cos(z)" in 23 let c_code = Codegen.compile_to_c f ["x"; "y"; "z"] in 24 print_endline c_code; 25 26 print_endline "horner form optimization\n"; 27 28 let poly = Parser.parse "x^4 + 2x^3 + 3x^2 + 4x + 5" in 29 let horner = Cse.horner_form poly "x" in 30 print_endline ("horner form: " ^ Expr.to_string horner); 31 32 print_endline "\nlimits computation\n"; 33 34 let limit_expr = Parser.parse "(sin(x)) / x" in 35 (match Limits.limit limit_expr "x" (Expr.Const 0.0) Limits.Bidirectional with 36 | Some result -> print_endline ("lim (sin(x)/x) as x→0 = " ^ Expr.to_string result) 37 | None -> print_endline "limit could not be computed"); 38 39 print_endline "\nsymbolic matrix operations\n"; 40 41 let m = Matrix.create 2 2 (fun i j -> 42 if i = j then Expr.Var (Printf.sprintf "a%d%d" i j) 43 else Expr.Var (Printf.sprintf "a%d%d" i j) 44 ) in 45 46 let det_m = Matrix.det m in 47 print_endline ("det = " ^ Expr.to_string det_m); 48 49 let trace_m = Matrix.trace m in 50 print_endline ("trace = " ^ Expr.to_string trace_m)