Euler method: Difference between revisions

(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)</lang>
 
(* 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 =
let results fn = recur ~until:(fun (t,y) -> Printf.printf "%7.3f %7.3f\n%!" t y; t >= 100.) fn (0.,100.)
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);
0.000 t >= 100.000
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
10.000 44.000
20 10.000 44.000 2759.20072682
30 20.000 27.200 2239.16072776
40 30.000 22.160 2029.64879651
50 40.000 20.194648 24.86481
60 50.000 20.058194 22.41579
70 60.000 20.017058 21.19965
80 70.000 20.017 20.00559573
90 80.000 20.005 20.00229583
100 90.000 20.002 20.00014690
100.000 20.000 20.07295
- : unit = ()
</pre>
Anonymous user