Normalise a list of numbers to the range 0 - 1

Update to fix $min == $max bug
use strict; use warnings; use List::MoreUtils qw(minmax); my @numbers = (23, 4, -6.5, 10.7, 123, 99.5); my ($min, $max) = minmax (@numbers); my $scale = 1.0 / ($max == $min ? $max : $max - $min); @numbers = map {($_ - $min) * $scale} @numbers; print join ", ", @numbers;

Replies are listed 'Best First'.
Re: Normalise numbers
by merlyn (Sage) on Nov 04, 2005 at 08:55 UTC

      You spotted the bug, but not the solution. You can't "scale" 0 to 1, you have to offset it. To handle that you would need to add another test to the code and adjust $min in the $min == $max special case:

      $min -= 1 if $min == $max;

      You can however offset anything to 0, so the bug fix has that result.


      Perl is Huffman encoded by design.