Tuesday, February 16, 2010

Standard Deviation in Perl

I recently wanted to figure out the average and standard deviation of a set of values in a perl script. Here's the script I created to do just that:

#!/usr/bin/perl

use strict;
use warnings;

my @my_array = (1,6,9,2,5,12,1);

my $average = average(@my_array);
my $std_dev = std_dev($average, @my_array);

printf "avg=%.2f, st. dev=%.2f\n", $average, $std_dev;

sub average {
my (@values) = @_;

my $count = scalar @values;
my $total = 0;
$total += $_ for @values;

return $count ? $total / $count : 0;
}

sub std_dev {
my ($average, @values) = @_;

my $count = scalar @values;
my $std_dev_sum = 0;
$std_dev_sum += ($_ - $average) ** 2 for @values;

return $count ? sqrt($std_dev_sum / $count) : 0;
}

No comments:

Post a Comment