Averages/Simple moving average: Difference between revisions

Content added Content deleted
(Added pony lang version of moving average)
No edit summary
Line 1,027: Line 1,027:
}</lang>
}</lang>
To avoid the floating point approximations keep piling up and growing, the code could perform a periodic sum on the whole circular queue array.
To avoid the floating point approximations keep piling up and growing, the code could perform a periodic sum on the whole circular queue array.
=={{header|Delphi}}==
{{Trans|Pascal}}
Small variation of [[#Pascal]].
<lang Delphi>
program Simple_moving_average;

{$APPTYPE CONSOLE}

type
TMovingAverage = record
private
buffer: TArray<Double>;
head: Integer;
Capacity: Integer;
Count: Integer;
sum, fValue: Double;
public
constructor Create(aCapacity: Integer);
function Add(Value: Double): Double;
procedure Reset;
property Value: Double read fValue;
end;

{ TMovingAverage }

function TMovingAverage.Add(Value: Double): Double;
begin
head := (head + 1) mod Capacity;
sum := sum + Value - buffer[head];
buffer[head] := Value;

if count < capacity then
begin
inc(Count);
fValue := sum / count;
exit(fValue);
end;
fValue := sum / Capacity;
Result := fValue;
end;

constructor TMovingAverage.Create(aCapacity: Integer);
begin
Capacity := aCapacity;
SetLength(buffer, aCapacity);
Reset;
end;

procedure TMovingAverage.Reset;
var
i: integer;
begin
head := -1;
Count := 0;
sum := 0;
fValue := 0;
for i := 0 to High(buffer) do
buffer[i] := 0;
end;

var
avg3, avg5: TMovingAverage;
i: Integer;

begin
avg3 := TMovingAverage.Create(3);
avg5 := TMovingAverage.Create(5);

for i := 1 to 5 do
begin
write('Inserting ', i, ' into avg3 ', avg3.Add(i): 0: 4);
writeln(' Inserting ', i, ' into avg5 ', avg5.Add(i): 0: 4);
end;

for i := 5 downto 1 do
begin
write('Inserting ', i, ' into avg3 ', avg3.Add(i): 0: 4);
writeln(' Inserting ', i, ' into avg5 ', avg5.Add(i): 0: 4);
end;

avg3.Reset;
for i := 1 to 100000000 do
avg3.Add(i);
writeln('100''000''000 insertions ', avg3.Value: 0: 4);

Readln;
end.</lang>
{{out}}
<pre>
Inserting 1 into avg3 1.0000 Inserting 1 into avg5 1.0000
Inserting 2 into avg3 1.5000 Inserting 2 into avg5 1.5000
Inserting 3 into avg3 2.0000 Inserting 3 into avg5 2.0000
Inserting 4 into avg3 3.0000 Inserting 4 into avg5 2.5000
Inserting 5 into avg3 4.0000 Inserting 5 into avg5 3.0000
Inserting 5 into avg3 4.6667 Inserting 5 into avg5 3.8000
Inserting 4 into avg3 4.6667 Inserting 4 into avg5 4.2000
Inserting 3 into avg3 4.0000 Inserting 3 into avg5 4.2000
Inserting 2 into avg3 3.0000 Inserting 2 into avg5 3.8000
Inserting 1 into avg3 2.0000 Inserting 1 into avg5 3.0000
100'000'000 insertions 99999999.0000
</pre>


=={{header|Dyalect}}==
=={{header|Dyalect}}==