Anonymous user
Averages/Simple moving average: Difference between revisions
Updated both D entries and their comments
(Updated both D entries and their comments) |
|||
Line 723:
=={{header|D}}==
===Using a Closure===
Currently this <code>sma</code> can't be @nogc because it allocates a closure on the heap. Some escape analysis could remove the heap allocation.
<lang d>import std.stdio, std.traits, std.algorithm;
auto sma(T, int period)() pure nothrow @safe {
T[period] data = 0;
T sum = 0;
int index, nFilled;
return (in T v) nothrow @safe @nogc {
sum += -data[index] + v;
data[index] = v;
Line 744 ⟶ 745:
foreach (immutable e; [1, 2, 3, 4, 5, 5, 4, 3, 2, 1])
writefln("Added %d, sma(3) = %f, sma(5) = %f", e, s3(e), s5(e));
}</lang>
{{out}}
Line 760:
===Using a Struct===
This version avoids the heap allocation of the closure
<lang d>import std.stdio, std.traits, std.algorithm;
Line 768:
int index, nFilled;
auto opCall(in T v) pure nothrow @safe @nogc {
sum += -data[index] + v;
data[index] = v;
Line 782:
foreach (immutable e; [1, 2, 3, 4, 5, 5, 4, 3, 2, 1])
writefln("Added %d, sma(3) = %f, sma(5) = %f", e, s3(e), s5(e));
}</lang>
To avoid the floating point approximations keep piling up and growing, the code
=={{header|E}}==
|