Jump to content

Averages/Simple moving average: Difference between revisions

Updated both D entry
(Updated both D entry)
Line 726:
 
auto sma(T, int period)() {
T[period] data = 0; // D FP are default-initialized to NaN
T sum = 0;
int index, nfillednFilled;
 
// return (in T v) nothrow {
return delegate (in T v) nothrow {
sum += -data[index] + v;
data[index] = v;
index = (index + 1) % period;
nfillednFilled = min(period, nfillednFilled + 1);
return cast(CommonType!(T, float))(sum) / nfillednFilled;
};
}
 
void main() {
autoimmutable s3 = sma!(int, 3)();
autoimmutable s5 = sma!(double, 5)();
 
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));
Line 759 ⟶ 758:
Added 2, sma(3) = 3.000000, sma(5) = 3.800000
Added 1, sma(3) = 2.000000, sma(5) = 3.000000</pre>
 
===Using a Struct===
This version avoids the heap allocation of the closure, same output:
Line 766:
T[period] data = 0;
T sum = 0;
int index, nfillednFilled;
 
auto opCall(in T v) pure nothrow {
Line 772:
data[index] = v;
index = (index + 1) % period;
nfillednFilled = min(period, nfillednFilled + 1);
return cast(CommonType!(T, float))(sum) / nfillednFilled;
}
}
Line 781:
SMA!(double, 5) s5;
 
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));
Cookies help us deliver our services. By using our services, you agree to our use of cookies.