Runge-Kutta method: Difference between revisions

Added Standard ML implementation
(Updated D entry)
(Added Standard ML implementation)
Line 992:
y(10) = 675.9999490 Error =5.09832864e-5
</pre>
 
=={{header|Standard ML}}==
<lang sml>fun step y' (tn,yn) dt =
let
val dy1 = dt * y'(tn,yn)
val dy2 = dt * y'(tn + 0.5 * dt, yn + 0.5 * dy1)
val dy3 = dt * y'(tn + 0.5 * dt, yn + 0.5 * dy2)
val dy4 = dt * y'(tn + dt, yn + dy3)
in
(tn + dt, yn + (1.0 / 6.0) * (dy1 + 2.0*dy2 + 2.0*dy3 + dy4))
end
 
(* Suggested test case *)
fun testy' (t,y) =
t * Math.sqrt y
 
fun testy t =
(1.0 / 16.0) * Math.pow(Math.pow(t,2.0) + 4.0, 2.0)
 
(* Test-runner that iterates the step function and prints the results. *)
fun test t0 y0 dt steps print_freq y y' =
let
fun loop i (tn,yn) =
if i = steps then ()
else
let
val (t1,y1) = step y' (tn,yn) dt
val y1' = y tn
val () = if i mod print_freq = 0 then
(print ("Time: " ^ Real.toString tn ^ "\n");
print ("Exact: " ^ Real.toString y1' ^ "\n");
print ("Approx: " ^ Real.toString yn ^ "\n");
print ("Error: " ^ Real.toString (y1' - yn) ^ "\n\n"))
else ()
in
loop (i+1) (t1,y1)
end
in
loop 0 (t0,y0)
end
 
(* Run the suggested test case *)
val () = test 0.0 1.0 0.1 101 10 testy testy'</lang>
Output
<pre>Time: 0.0
Exact: 1.0
Approx: 1.0
Error: ~1.11022302463E~16
 
Time: 1.0
Exact: 1.5625
Approx: 1.56249985428
Error: 1.45722452549E~07
 
Time: 2.0
Exact: 4.0
Approx: 3.99999908052
Error: 9.19479203443E~07
 
Time: 3.0
Exact: 10.5625
Approx: 10.5624970904
Error: 2.90956245586E~06
 
Time: 4.0
Exact: 25.0
Approx: 24.9999937651
Error: 6.23490938878E~06
 
Time: 5.0
Exact: 52.5625
Approx: 52.5624891803
Error: 1.08196973727E~05
 
Time: 6.0
Exact: 100.0
Approx: 99.9999834054
Error: 1.65945961186E~05
 
Time: 7.0
Exact: 175.5625
Approx: 175.562476482
Error: 2.35177280956E~05
 
Time: 8.0
Exact: 289.0
Approx: 288.999968435
Error: 3.15651997767E~05
 
Time: 9.0
Exact: 451.5625
Approx: 451.562459277
Error: 4.07231581221E~05
 
Time: 10.0
Exact: 676.0
Approx: 675.999949017
Error: 5.09832866555E~05</pre>
 
=={{header|Tcl}}==
Anonymous user