<?xml version="1.0" encoding="windows-1252"?>
<node id="972016" title="Re^2: calculate average in sliding windows" created="2012-05-23 07:47:10" updated="2012-05-23 07:47:10">
<type id="11">
note</type>
<author id="888573">
Eliya</author>
<data>
<field name="doctext">
&lt;p&gt; A less computationally intensive variant would be to directly maintain a &lt;c&gt;$sum&lt;/c&gt;, to which you add/subtract individual values (instead of push/shift on an array, from which you then recompute the sum every time): &lt;/p&gt;
&lt;c&gt;
#!/usr/bin/perl -lw
use strict;
use constant WINDOW =&gt; 10;

#my @data  = map int( rand 10 ), 1 .. 30;
my @data = qw(3 8 8 2 5 5 0 3 8 3 2 3 2 3 5 4 8 7 5 4 6 3 1 6 3 6 0 7 3 3);

my @mAves;
my $sum = 0;
for my $i (0..$#data) {
    $sum += $data[$i];
    $sum -= $data[$i-WINDOW()] if $i &gt;= WINDOW;
    push @mAves, $sum / WINDOW if $i &gt;= WINDOW-1;
}

print join ' ', @data;
print join '   ', @mAves;

__END__
3 8 8 2 5 5 0 3 8 3 2 3 2 3 5 4 8 7 5 4 6 3 1 6 3 6 0 7 3 3
4.5   4.4   3.9   3.3   3.4   3.4   3.3   4.1   4.5   4.2   4.3   4.7   4.7   4.6   4.9   4.7   4.9   4.1   4.1   3.9   3.8
&lt;/c&gt;</field>
<field name="root_node">
971993</field>
<field name="parent_node">
971998</field>
</data>
</node>
