XP is just a number PerlMonks

### Re^3: calculate average in sliding windows

by marfabe (Initiate)
 on May 23, 2012 at 14:43 UTC ( #972048=note: print w/replies, xml ) Need Help??

in reply to Re^2: calculate average in sliding windows
in thread calculate average in sliding windows

Thanks Eliya
Here's the simplified sample set

```position     value
1    1
10    3
30    1
40    2
60    2

And here the output for window size of 30

```1-30   1.666666667
31-60  2

Replies are listed 'Best First'.
Re^4: calculate average in sliding windows
by Eliya (Vicar) on May 23, 2012 at 15:05 UTC

Ok, thanks.  So maybe like this?

```#!/usr/bin/perl -lw
use strict;
use constant WINDOW => 30;

my \$sum = 0;
my \$n   = 0;
my \$p   = WINDOW;

while (<DATA>) {
my (\$pos, \$val) = split;
if (eof) {  # corner case
\$sum += \$val;
\$n++;
}
if (\$pos > \$p or eof) {
print \$sum / \$n if \$n > 0;
\$sum = 0;
\$n = 0;
\$p += WINDOW while \$pos > \$p;
}
\$sum += \$val;
\$n++;
}

__DATA__
1    1
10    3
30    1
40    2
60    2

Output:

```1.66666666666667
2

(Upd: fixed handling of corner case)

Yes!! It works perfectly! Thank you!

Create A New User
Node Status?
node history
Node Type: note [id://972048]
help
Chatterbox?
 [Corion]: Hmm - HTC Vive reduces its price to EUR 700 (from EUR 900). Now I have to look what graphics cards prices are - maybe a good enough VR rig can be had for EUR 1500 now instead of EUR 2000(+)

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (7)
As of 2017-08-21 08:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
Who is your favorite scientist and why?

Results (319 votes). Check out past polls.

Notices?