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.
In reply to Re^2: A small question on file comparison
by ack
in thread A small question on file comparison
by pavanvidem
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |