RosettaCodeData/Task/Euler-method/D/euler-method.d

23 lines
736 B
D
Raw Permalink Normal View History

2015-02-20 00:35:01 -05:00
import std.stdio, std.range, std.traits;
2013-04-10 16:57:12 -07:00
2015-02-20 00:35:01 -05:00
/// Approximates y(t) in y'(t)=f(t,y) with y(a)=y0 and t=a..b and the step size h.
void euler(F)(in F f, in double y0, in double a, in double b, in double h) @safe
if (isCallable!F && __traits(compiles, { real r = f(0.0, 0.0); })) {
2013-04-10 16:57:12 -07:00
double y = y0;
2015-02-20 00:35:01 -05:00
foreach (immutable t; iota(a, b, h)) {
2013-04-10 16:57:12 -07:00
writefln("%.3f %.3f", t, y);
y += h * f(t, y);
}
2015-02-20 00:35:01 -05:00
"done".writeln;
2013-04-10 16:57:12 -07:00
}
void main() {
2015-02-20 00:35:01 -05:00
/// Example: Newton's cooling law.
enum newtonCoolingLaw = (in double time, in double t)
pure nothrow @safe @nogc => -0.07 * (t - 20);
2013-04-10 16:57:12 -07:00
2015-02-20 00:35:01 -05:00
euler(newtonCoolingLaw, 100, 0, 100, 2);
euler(newtonCoolingLaw, 100, 0, 100, 5);
euler(newtonCoolingLaw, 100, 0, 100, 10);
2013-04-10 16:57:12 -07:00
}