in reply to A small question on file comparison

If you know that you want a specific precision, such as 5 decimal places, try something like this:
use strict; use warnings; my $n1 = 35.152000; my $n2 = 35.152001; if (abs($n1 - $n2) < 0.000_009) { print 'equal' } else { print 'not equal' } __END__ equal

Replies are listed 'Best First'.
Re^2: A small question on file comparison
by ack (Deacon) on Mar 14, 2010 at 05:40 UTC

    Here is a version (admittedy much more compicated and there is probably a more eficient approach) that doesn;t require that you know beforehand how many significant figures are expected in the comparison.

    #!/usr/bin/perl use strict; use warnings; my $n1 = 35.152000; my $n2 = 35.152001; my $tol = 1; if(doTest($n1,$n2,$tol)){ print "Strings are the same\n"; } else { print "Strings are not the same\n"; } exit(0); sub doTest { my($n1,$n2,$tol) = @_; $n1 =~ /(\d*)\.?(\d*)/; my ($intPart1,$fracPart1) = ($1,$2); $n2 =~ /(\d*)\.?(\d*)/; my ($intPart2,$fracPart2) = ($1,$2); my $numSigFigs1; my $numSigFigs2; if($fracPart1 ne ''){ $numSigFigs1 = -length($fracPart1); if($fracPart2 ne ''){ $numSigFigs2 = -length($fracPart2); } else { $numSigFigs2 = 0; } } else { $numSigFigs1 = 0; if($fracPart2 ne ''){ $numSigFigs2 = -length($fracPart2); } else { $numSigFigs2 = 0; } } # ensure that the highest precision number controls whose'last digi +t' we # are comparing my $sigFigs = $numSigFigs1; $sigFigs = $numSigFigs2 if($numSigFigs2 < $numSigFigs1); my $test = $tol * 10**($sigFigs); # use the sprintf() function to be sure that there aren;t any stray + diits # way out beyond the number o significant figures you're interested + in # that interfere with the test using abs($n1-$n2) <= $test. if(sprintf("%.*f",abs($sigFigs),abs($n1 - $n2)) <= $test){ return 1; # strings are the same within tolrance $tol } else { return 0; # strings are not the same within tolerance $tol } } # end sub doTest()

    I have tested this with a variety of vakues ranging from integers to a variety of floating points (with same number of significant figures and some with mixed numbers of significant figures) and it appears to work on all such cases. It does not, however work with hex or octal numbers. Also note that the variable $tol is used to set how far off the two 'last digits' can be and sti be onsidered to 'match' (e.g., the OP set this vaue to 1 ... that is +/- 1).</pp>

    I hope this helps.

    ack Albuquerque, NM
Re^2: A small question on file comparison
by pavanvidem (Initiate) on Mar 14, 2010 at 02:29 UTC
    Thank you very much for reply. Even i had the same idea, but could you please tell me how can i compare two such complete files using your idea with less time complexity?
      less time complexity
      I do not understand what you mean by that. At this point, I think you should show what Perl code you have tried, what output you expect, and your actual output. Please show several examples.