chaoticset has asked for the wisdom of the Perl Monks concerning the following question:
That's why I need help...!
This is essentially unedited; I decided I needed a standard deviation sub, so I wrote one. Then I remembered that I should get some of my code looked at for stylistic errors (and/or efficiency problems) and I figured, "Why not?" I stuck a little test of the sub on the end, and, here it is.
Be forewarned: This is probably bad code. This is most likely bad *design*. I'm using the shotgun theory here, which is essentially "code it and see what happens". I'm not good at any of this yet. You were warned.
Could this have been shorter? Should it have been longer? Is there some convention of math subs that's normally followed that I (forgot|don't know about)? Did I leave something out? Did I leave something in?#!c:\perl\bin\perl.exe -w use strict; use warnings; # This subroutine, given a set of values, should return the standard +deviation. sub standard_deviation { my $mean = 0; my $sample_size; my @differences; for (@_) { $mean = $mean + $_; } $sample_size = scalar(@_); $mean = $mean/$sample_size; for (@_) { @differences = (@differences, (($_-$mean)*($_-$mean))); } my $standard = 0; for (@differences) { $standard = $standard + $_; } $standard = sqrt($standard/$sample_size); return $standard; } my $stddev; my @values; @values = (22, 17, 29, 39, 20, 32); $stddev = standard_deviation(@values); print "The standard deviation is $stddev.";
Anything at all, whatever it is, if it's not quite right or it just looks bad, please, let me know.
-----------------------
You are what you think.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Code Review! Go Ahead, Rip It Up!
by japhy (Canon) on Jan 13, 2002 at 04:20 UTC | |
|
Re: Code Review! Go Ahead, Rip It Up!
by VSarkiss (Monsignor) on Jan 13, 2002 at 04:04 UTC | |
|
Re: Code Review! Go Ahead, Rip It Up!
by dws (Chancellor) on Jan 13, 2002 at 04:05 UTC | |
|
Re: Code Review! Go Ahead, Rip It Up!
by blakem (Monsignor) on Jan 13, 2002 at 04:14 UTC | |
|
Re: Code Review! Go Ahead, Rip It Up!
by toma (Vicar) on Jan 13, 2002 at 15:34 UTC | |
|
Re: Code Review! Go Ahead, Rip It Up!
by s0ttle (Scribe) on Jan 13, 2002 at 10:48 UTC |