Standard Deviation – Perl Script

code

When you need to be more accurate than average, you need standard deviation bro…


#!/usr/bin/perl
use strict;

print standard_deviation(1,2,3,4,5,6,7,8,9,10)."\n";

sub standard_deviation {
my(@numbers) = @_;
#Prevent division by 0 error in case you get junk data
return undef unless(scalar(@numbers));

# Step 1, find the mean of the numbers
my $total1 = 0;
foreach my $num (@numbers) {
$total1 += $num;
}
my $mean1 = $total1 / (scalar @numbers);

# Step 2, find the mean of the squares of the differences
# between each number and the mean
my $total2 = 0;
foreach my $num (@numbers) {
$total2 += ($mean1-$num)**2;
}
my $mean2 = $total2 / (scalar @numbers);

# Step 3, standard deviation is the square root of the
# above mean
my $std_dev = sqrt($mean2);
return $std_dev;
}

3 thoughts on “Standard Deviation – Perl Script

  1. Here’s a rewrite of your standard deviation script in ruby if any of your visitors would be into that sort of thing:

    #!/usr/bin/env ruby
    #

    def standard_deviation(*numbers)
    return if numbers.size == 0
    count = numbers.size

    sum = numbers.reduce(&:+).to_f
    mean = sum / count

    sum_of_squares = numbers.reduce(0) { |r, n|
    r + ((n – mean).abs ** 2)
    }

    variance = sum_of_squares / count

    Math.sqrt(variance)
    end

    puts standard_deviation(1,2,3,4,5,6,7,8,9,10)

  2. And here is the same program implemented in Haskell:

    stdDev :: Floating a => [a] -> a

    –What we get if we have an empty list
    stdDev [] = 0

    –Take square root of the Variance
    stdDev xs = sqrt $ (sum $ map (^2) xs) / l – (sum xs / l) ^ 2
    where l = fromIntegral $ length xs

Leave a Reply to codeswish Cancel reply

Your email address will not be published. Required fields are marked *