Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re^4: calculate average in sliding windows

by Eliya (Vicar)
on May 23, 2012 at 15:05 UTC ( #972051=note: print w/ replies, xml ) Need Help??


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

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)


Comment on Re^4: calculate average in sliding windows
Select or Download Code
Replies are listed 'Best First'.
Re^5: calculate average in sliding windows
by marfabe (Initiate) on May 23, 2012 at 15:31 UTC

    Yes!! It works perfectly! Thank you!

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://972051]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (16)
As of 2015-07-07 19:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (93 votes), past polls