Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

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

by hanspr (Sexton)
on Mar 31, 2012 at 20:24 UTC ( [id://962795]=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://962795]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (9)
As of 2024-04-23 17:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found