Averages/Simple moving average: Difference between revisions

Content added Content deleted
m (moved Moving Average to Average/Simple moving average: collecting all averages under a common prefix)
(→‎{{header|D}}: add implementation)
Line 146: Line 146:
(setf pointer (rest pointer)) ; advance pointer
(setf pointer (rest pointer)) ; advance pointer
(/ sum (min count period))))</lang>
(/ sum (min count period))))</lang>

=={{header|D}}==
This should work properly for any types that act like numerics.
<lang d>
import std.stdio;
import std.string;

class MovingAvg(T) {
T accum = 0;
int numelements;
MovingAvg!(T) add(T input) {
accum += input;
numelements++;
return this;
}
T getAvg() {
if (!numelements) return 0;
return accum/numelements;
}
}

int main() {
double[]nums = [1, 2, 3, 4, 5, 5, 4, 3, 2, 1];
auto mavg = new MovingAvg!(double);
foreach(index,num;nums) {
writefln("Average number %d is %s",index,toString(mavg.add(num).getAvg));
}
return 0;
}
</lang>


=={{header|E}}==
=={{header|E}}==