in reply to Comparing numbers

Hi,
sounds to me like homework.
But ok.
I would write it so :
#!/usr/local/perl -w use strict; use warnings; my @file = ('0.13','0.14','0.14'); my $diff = 0; my @diffVal; for (my $i=1 ; $i< scalar(@file) ; $i++){ if ($diff < abs($file[$i-1]-$file[$i])){ $diff = abs($file[$i-1]-$file[$i]); $diffVal[0] = $file[$i-1]; $diffVal[1] = $file[$i]; } } print "Difference between $diffVal[0] and $diffVal[1] is $diff\n" if ( +defined($diffVal[1]));
(It is not optimized!)

Replies are listed 'Best First'.
Re: Comparing numbers
by Abigail-II (Bishop) on Nov 29, 2002 at 11:21 UTC
    What's the point of using -w and use warnings? And why quote numbers? Also, your code seems to fail if all numbers are equal - it won't generate output.

    Abigail

      ok, -w and use warnings don't make sense.
      Yes, you are correct with the equal - output and the numbers.
      change
      my @file = ('0.13','0.14','0.14'); my $diff = 0;
      to
      my @file = (0.14,0.14); my $diff = -1;
      and here you got your output
      Difference between 0.14 and 0.14 is 0
Re: Re: Comparing numbers
by jreades (Friar) on Nov 29, 2002 at 11:28 UTC

    You could also have some fun doing something like this:

    my @numbers = ('0.13', '0.14', '0.14', '0.19', '0.21', '0.23', '0.45') +; my %differences = (); for (my $i = 0; $i < scalar(@numbers); $i++) { next if $i == 0; push @{$differences{($numbers[$i] - $numbers[$i - 1])}}, $numb +ers[$i] . " - " . $numbers[$i - 1]; } foreach (sort keys %differences) { print STDOUT "Difference ($_) occured: ", join (', ', @{$diffe +rences{$_}}), "\n" } exit 0;

    I guess that's going beyond the exercise a little bit, but kind of fun and turned out this:

    Difference (0) occured: 0.14 - 0.14 Difference (0.01) occured: 0.14 - 0.13 Difference (0.02) occured: 0.21 - 0.19, 0.23 - 0.21 Difference (0.05) occured: 0.19 - 0.14 Difference (0.22) occured: 0.45 - 0.23