March 2014 update

This commit is contained in:
Ingy döt Net 2014-04-02 16:56:35 +00:00
parent 09687c4926
commit a25938f123
1846 changed files with 21876 additions and 5203 deletions

View file

@ -1,25 +1,24 @@
import std.stdio, std.traits, std.algorithm;
auto sma(T, int period)() {
T[period] data = 0; // D FP are default-initialized to NaN
T[period] data = 0;
T sum = 0;
int index, nfilled;
int index, nFilled;
// return (in T v) nothrow {
return delegate (in T v) nothrow {
return (in T v) nothrow {
sum += -data[index] + v;
data[index] = v;
index = (index + 1) % period;
nfilled = min(period, nfilled + 1);
return cast(CommonType!(T, float))sum / nfilled;
nFilled = min(period, nFilled + 1);
return CommonType!(T, float)(sum) / nFilled;
};
}
void main() {
auto s3 = sma!(int, 3)();
auto s5 = sma!(double, 5)();
immutable s3 = sma!(int, 3);
immutable s5 = sma!(double, 5);
foreach (e; [1, 2, 3, 4, 5, 5, 4, 3, 2, 1])
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));
}

View file

@ -3,14 +3,14 @@ import std.stdio, std.traits, std.algorithm;
struct SMA(T, int period) {
T[period] data = 0;
T sum = 0;
int index, nfilled;
int index, nFilled;
auto opCall(in T v) pure nothrow {
sum += -data[index] + v;
data[index] = v;
index = (index + 1) % period;
nfilled = min(period, nfilled + 1);
return cast(CommonType!(T, float))sum / nfilled;
nFilled = min(period, nFilled + 1);
return CommonType!(T, float)(sum) / nFilled;
}
}
@ -18,7 +18,7 @@ void main() {
SMA!(int, 3) s3;
SMA!(double, 5) s5;
foreach (e; [1, 2, 3, 4, 5, 5, 4, 3, 2, 1])
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));
}