Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

A quick question, just to save my hairy ass at work: How do I find the median value from a file(or array) in perl. More precisely, if there are n items in a ordered list and n is odd, there is a single median at location (n+1)/2-1. If n is even, there are two medians at locations n/2-1 and n/2. But how does one distinguish if a value is odd or even under perl? Is there an algorithm to divide the number of values by two and see if the result is a fraction or not?

Replies are listed 'Best First'.
Re: how to find median value
by merlyn (Sage) on Jun 22, 2001 at 19:58 UTC
    One cheap way is to simply always take the average of two elements, and let the truncation of indicies handle finding the right elements, which will collapse to adding the same element twice if the list is odd.
    sub median { my @sorted = sort { $a <=> $b } @_; ($sorted[$#sorted/2 + 0.1] + $sorted[$#sorted/2 + 0.6])/2; }

    -- Randal L. Schwartz, Perl hacker

(jeffa) Re: how to find median value
by jeffa (Bishop) on Jun 22, 2001 at 19:46 UTC
    CPAN solution!

    Statistics::Descriptive. If you need more info, just look at the source code!

    Jeff

    R-R-R--R-R-R--R-R-R--R-R-R--R-R-R--
    L-L--L-L--L-L--L-L--L-L--L-L--L-L--
    
      i need to know how to find the median of a set of numbers
Re: how to find median value
by mpolo (Chaplain) on Jun 22, 2001 at 19:46 UTC
    Why yes, $a % $b returns the remainder when $a is integer divided by $b. See perlman:perlop for more info.

    So just sort the list and then determine which answer to give using the modulo operator %.

    Note that some authors consider the median of a list with an even number of elements to be the arithmetic mean of locations n/2-1 and n/2.

Re: how to find median value
by Albannach (Monsignor) on Jun 22, 2001 at 19:56 UTC
Re: how to find median value
by Gloom (Monk) on Jun 22, 2001 at 19:46 UTC
    Short answer ( I'm late :)
    sub is_odd { return ( $_[0] % 2 ) != 0 ; }

    __________________________
    Hope this helps