Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Statistic in Perl(Using Subroutines)

by stamp1982 (Novice)
on Jul 10, 2013 at 22:19 UTC ( #1043577=perlquestion: print w/ replies, xml ) Need Help??
stamp1982 has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks

So I have three sets of data and I am trying to write a program that would calculate and print out for each of the data sets: number of measurements, average, variance and standard deviation (a subroutine should be used to do all). The program should also call the subroutines for each data set and print out the results.

So far this is what I have for the average. Please let me know where there are mistakes and how to proceed.
use strict; use warnings; my @Dset1 = (5, 6, 7 , 8, 10); my @Dset2= (10,11,12); my @Dset3 = (16,48,49); Data('Info',@Dset1); Data('Info',@Dset2); Data('Info',@Dset3); my $avg = average(\@data); print "The average is $avg \n"; sub average { @_ == 1 or die ('Sub usage: $average = average(\@array);'); my ($array_ref) = @_; my $sum; my $count = scalar @$array_ref; foreach (@$array_ref) { $sum += $_; } return $sum / $count; }

Comment on Statistic in Perl(Using Subroutines)
Download Code
Replies are listed 'Best First'.
Re: Statistic in Perl(Using Subroutines)
by toolic (Bishop) on Jul 11, 2013 at 01:04 UTC
Re: Statistic in Perl(Using Subroutines)
by jwkrahn (Monsignor) on Jul 10, 2013 at 23:09 UTC
    sub average { @_ == 1 or die ('Sub usage: $average = average(\@array);'); my ($array_ref) = @_; my $sum; my $count = scalar @$array_ref; foreach (@$array_ref) { $sum += $_; } return $sum / $count; }
    sub average { ref( my $array_ref = $_[ 0 ] ) eq 'ARRAY' or die 'Sub usage: $average = average(\@array);'; my $sum; $sum += $_ for @$array_ref; return $sum / @$array_ref; }

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (15)
As of 2015-09-03 15:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My preferred temperature scale is:










    Results (117 votes), past polls