Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: perl subtraction

by lyklev (Pilgrim)
on Jan 10, 2010 at 22:06 UTC ( [id://816648]=note: print w/replies, xml ) Need Help??


in reply to perl subtraction

As previous posts have mentioned, floating point numbers are only stored in a limited precision. If your number can be written in a binary non-repeating decimal , your ok, but for repeating floating point numbers in binary way, some accuracy is lost. For example, 1/4th can be written as a binary non-repeating decimal, (1/4 = 0.01 binary), but 1/5th is repeating in binary form (1/5 = 0.00110011...) and will get truncated. This means that for a computer, 1/5 is not 0.2!

The important lesson is that you should never (I mean it!) compare floating point numbers for equality. By the way, this goes for most programming languages.

To solve your problem, write the numbers as a formatted string wide enough, and compare those. For example:

my $val1 = 17554.61 - 2194.33; my $val2 = 19748.94; my $val1_str = sprintf("12.2f", $val1); my $val2_str = sprintf("12.2f", $val2); print ("equal\n") if ($val1_str eq $val2_str);

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (3)
As of 2024-04-24 14:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found