in reply to Calculating statistical median

sub mean { my ($arrayref) = @_; my $result; foreach (@$arrayref) { $result += $_ } return $result / @$arrayref; } my @points = qw(1 2 3 4); print mean \@points;

Replies are listed 'Best First'.
Re^2: Calculating statistical median
by revdiablo (Prior) on Jul 13, 2005 at 17:08 UTC

    The original post pretty clearly states that he wants the median. Why you posted a snippet that calculates the mean is beyond me. update: Maybe the original post was updated at some point without notice?

Re^2: Calculating statistical median
by jimbojones (Friar) on Jul 13, 2005 at 15:35 UTC
    Hi.

    Is there a special reason for the array reference? Versus this?
    sub mean { my $result; foreach (@_) { $result += $_ } return $result / @_; } my @points = qw(1 2 3 4); print mean @points;
      Copying an array or hash into @_ takes time. Passing arrays and hashes by reference is straightforward.
      See Benchmark
      If you want median:
      sub median { $_[0]->[ @{$_[0]} / 2 ] } my @points = 0..100; print median(\@points), "\n";

        It should sort the array before calculating median this way. Besides that it does not handle the array with even elements correctly.

        This calculates median only if @points is already truly ordered.
        This sample has a bug: if input array is not sorted, the result is incorrect.
        $ cat median.pl sub median { $_[0]->[ @{$_[0]} / 2 ] } my @sample=(9, 1, 2, 3, 4, 8, 7, 6, 5); my @sorted; @sorted=sort @sample; print median(\@sample),"\n"; print median(\@sorted),"\n"; $ perl median.pl 4 5 $
        Should be
        5 5
        Hi

        Thanks. Didn't know about the speed issue.

        - j