Runge-Kutta method: Difference between revisions
Content deleted Content added
m Better integration of WP link |
+ D entry |
||
Line 85: | Line 85: | ||
y(9.0) = 451.56245928 Error: 4.07232E-05 |
y(9.0) = 451.56245928 Error: 4.07232E-05 |
||
y(10.0) = 675.99994902 Error: 5.09833E-05</pre> |
y(10.0) = 675.99994902 Error: 5.09833E-05</pre> |
||
=={{header|D}}== |
|||
{{trans|Ada}} |
|||
<lang d>import std.stdio, std.math; |
|||
alias real FP; |
|||
void runge(in FP function(in FP, in FP) pure nothrow yp_func, |
|||
FP[] t, FP[] y, in FP dt) pure nothrow { |
|||
foreach (n; 0 .. t.length - 1) { |
|||
FP dy1 = dt * yp_func(t[n], y[n]); |
|||
FP dy2 = dt * yp_func(t[n] + dt / 2.0, y[n] + dy1 / 2.0); |
|||
FP dy3 = dt * yp_func(t[n] + dt / 2.0, y[n] + dy2 / 2.0); |
|||
FP dy4 = dt * yp_func(t[n] + dt, y[n] + dy3); |
|||
t[n + 1] = t[n] + dt; |
|||
y[n + 1] = y[n] + (dy1 + 2.0 * (dy2 + dy3) + dy4) / 6.0; |
|||
} |
|||
} |
|||
FP calc_err(in FP t, in FP calc) pure nothrow { |
|||
immutable FP actual = (t ^^ 2 + 4.0) ^^ 2 / 16.0; |
|||
return abs(actual - calc); |
|||
} |
|||
void main() { |
|||
enum FP dt = 0.10; |
|||
enum size_t N = 101; |
|||
FP[N] t_arr, y_arr; |
|||
t_arr[0] = 0.0; |
|||
y_arr[0] = 1.0; |
|||
runge((t, y) => t * sqrt(y), t_arr, y_arr, dt); |
|||
foreach (i; 0 .. t_arr.length) |
|||
if (i % 10 == 0) |
|||
writefln("y(%.1f) = %.8f Error: %.6g", |
|||
t_arr[i], y_arr[i], |
|||
calc_err(t_arr[i], y_arr[i])); |
|||
}</lang> |
|||
{{out}} |
|||
<pre>y(0.0) = 1.00000000 Error: 0 |
|||
y(1.0) = 1.56249985 Error: 1.45722e-07 |
|||
y(2.0) = 3.99999908 Error: 9.19479e-07 |
|||
y(3.0) = 10.56249709 Error: 2.90956e-06 |
|||
y(4.0) = 24.99999377 Error: 6.23491e-06 |
|||
y(5.0) = 52.56248918 Error: 1.08197e-05 |
|||
y(6.0) = 99.99998341 Error: 1.65946e-05 |
|||
y(7.0) = 175.56247648 Error: 2.35177e-05 |
|||
y(8.0) = 288.99996843 Error: 3.15652e-05 |
|||
y(9.0) = 451.56245928 Error: 4.07232e-05 |
|||
y(10.0) = 675.99994902 Error: 5.09833e-05</pre> |
|||
=={{header|Tcl}}== |
=={{header|Tcl}}== |