Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Answer: My floating point comparison does not work. Why ?

by hanspr (Acolyte)
on Mar 31, 2012 at 20:24 UTC ( #962795=categorized answer: print w/replies, xml ) Need Help??

Q&A > math > My floating point comparison does not work. Why ? - Answer contributed by hanspr


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

Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (4)
As of 2021-01-18 07:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?