When doing Project 2 I realized that I have problems with handling loops. I have solved everything except for the calculation of the variance. My idea is that I should construct a loop which takes each element, subtracts it from the mean, squares it and sums all elements up. However, I can't figure out how to do the squaring with the available commands. {$i ** 2} doesn't seem to do the job. Also, it would be convenient if I was able to tell the loop to perform more than one computation on the elements, but I can't figure out how to do that.
I'm probably overlooking some obvious solution which has been discussed in the tutorial, and I just need a nudge in the right direction. Here is my script this far:
#!/usr/bin/perl
#
stats.pl by Disa
use strict; use warnings;
die "usage:
stats.pl <number1> <number2> <etc>\n" unless @ARGV > 1;
# sum and mean
my @array = @ARGV;
my $length = @array;
my $sum = 0;
foreach my $i (@array) {$sum += $i}
my $mean = $sum / $length;
print "count: $length \t sum: $sum\t mean: $mean\n";
#median, min and max
my @sorted_array = sort {$a <=> $b} @array;
my $min = $sorted_array[0];
my $max = $sorted_array[$length - 1];
my $even_median = ($sorted_array[$length / 2] + $sorted_array[($length / 2) - 1]) / 2;
my $odd_median = $sorted_array [$length / 2];
print "min: $min \t max: $max \t ";
if ($length % 2 == 0) {print "median: $even_median\n"}
elsif ($length % 2 == 1) {print "median: $odd_median\n"}
# Variance: 1)calculated each elements difference from the mean
my @diff = "";
foreach my $i (@array) {push (@diff, $mean -$i)}
my $diff = join(", ", @diff);
print $diff, "\n";
#How to square each element and sum them up???
#my $variance = $mean / $length;
#print "variance: $variance\n";
#calculate stdev with sqrt($variance)
-------------------------------------------------------------------------
Output:
stats.pl 2 3 4 1 5
count: 5 sum: 15 mean: 3
min: 1 max: 5 median: 3
, 1, 0, -1, 2, -2
Great course by the way. It's my first time programming and I find it very challenging and fun!
/Disa