Anonymous user
Euler method: Difference between revisions
→{{header|OCaml}}
(Added OCaml solution) |
|||
Line 1,264:
(* newton_cooling doesn't use time parameter, so _ is a placeholder *)
let newton_cooling ~k ~tr _ y = -.k *. (y -. tr)
(* analytic solution for Newton cooling *)
let analytic_solution ~k ~tr ~t0 t = tr +. (t0 -. tr) *. exp (-.k *. t)</lang>
Using the above functions to produce the task results:
<lang OCaml>(* Wrapping up the parameters in a "cool" function: *)
let cool = euler (newton_cooling ~k:0.07 ~tr:20.)
(* Similarly for the analytic solution: *)
let analytic = analytic_solution ~k:0.07 ~tr:20. ~t0:100.
(* (Just a loop) Apply recurrence function on state, until some condition *)
Line 1,278 ⟶ 1,284:
(* 'results' generates the specified output starting from initial values t=0, temp=100C; ending at t=100s *)
let results fn =
Printf.printf "\t time\t euler\tanalytic\n%!";
let until (t,y) =
Printf.printf "\t%7.3f\t%7.3f\t%9.5f\n%!" t y (analytic t);
in recur ~until fn (0.,100.)
results (cool ~step:10.)
Line 1,287 ⟶ 1,298:
<pre>
# results (cool ~step:10.);;
time euler analytic
▲ 0.000 100.000
0.000 100.000 100.00000
100.000 20.000 20.07295
- : unit = ()
</pre>
|