[lug] Perl, sorting hashtables by value, and floating-point

Chris Riddoch chris-blug at syntacticsugar.org
Mon May 31 18:16:32 MDT 2004


Hi, everyone.

I have a bit of a Perl question.  I've got a very large hash table,
where all values are floating point numbers all between 0 and .001 or
so.  (They're very tiny probabilities) It's the fourth through tenth
digits that I really give a darn about, because that's where they
really start looking different.  Perl supposedly represents floating
point numbers as doubles, which is fine; on the 64-bit Opteron,
doubles are way more than big enough for what I need.

Okay, here's the standard Perl idiom for sorting a hash numerically by
value:

foreach my $k (sort { $a <=> $b} keys %hash) {
    print $hash{$k} . " = " . $k . "\n";
}

This completely fails to work when those numbers are floating point.
I've tried precomputing logarithms to make the numbers more easily
computable, with no change in Perl's sorting ability.  I've tried 'use
bignum' in case it might help, but it seems to overload everything but
the spaceship (<=>) operator.

I'm certain there's a way to do this.  

Ideas?

-- 
epistemological humility
   - Chris Riddoch -




More information about the LUG mailing list