http://qs321.pair.com?node_id=962795


in reply to My floating point comparison does not work. Why ?


If you create a text file x.txt with following data
227.20 1176.00 262.00 481.60 492.00 489.60 808.50 934.50 150.00 806.00 563.70 295.60 552.90 327.25 0.00 0.00 0.00
Then file x2.txt
7566.85
And then run this code
open (X,"< x.txt"); while ($n = <X>) { $n =~ s/\n|\r//g; # same with or without $t += $n; } close X; $st = `cat x2.txt`; $st =~ s/\n|\r//g; # same with or without print "t = $t\n"; print "st = $st\n"; if (equal($t,$st,5)) { print "Equal\n"; } else { print "Different\n"; } sub equal { my ($A,$B,$dp) = @_; return sprintf("%.${dp}g",$A) eq sprintf("%.${dp}g",$B); }
The result is
t = 7566.85 st = 7566.85 Different
So the only reliable solution I have found till now is
sub equal { my ($A,$B,$dp) = @_; if ($A == $B) { return 1; } elsif ($A eq $B) { return 1; } return sprintf("%.${dp}g",$A) eq sprintf("%.${dp}g",$B); }
Result
t = 7566.85 st = 7566.85 Equal