Wednesday, May 22, 2013

Calculating the average and standard deviation in perl


Calculating the average and standard deviation in perl

The following two subroutines can be used as a drop in replacement for Math::NumberCruncher. This is useful when trying to limit the number of dependencies of your perl script.
 
sub average{
        my($data) = @_;
        if (not @$data) {
                die("Empty array\n");
        }
        my $total = 0;
        foreach (@$data) {
                $total += $_;
        }
        my $average = $total / @$data;
        return $average;
}
sub stdev{
        my($data) = @_;
        if(@$data == 1){
                return 0;
        }
        my $average = &average($data);
        my $sqtotal = 0;
        foreach(@$data) {
                $sqtotal += ($average-$_) ** 2;
        }
        my $std = ($sqtotal / (@$data-1)) ** 0.5;
        return $std;
}
Usage:
$ave = &average(\@array);
#$ave = Math::NumberCruncher::Average(\@array); //OLD WAY
$std = &stdev(\@array);
#$std = Math::NumberCruncher::StandardDeviation(\@array); //OLD WAY

No comments:

Post a Comment