|Pathologically Eclectic Rubbish Lister|
My floating point comparison does not work. Why ?by thens (Scribe)
|on Sep 23, 2003 at 05:29 UTC||Need Help??|
You want to compare two floating point numbers and perl complains that they are not equal even though they are equal.
The output is
Well, by now you should be thinking perl is crazy. Let me explain what happens here.
The floating point numbers are stored in binary format in the computer and even though 10/100 = 0.1 is a finite decimal in base 10 arithmetic, when converted to binary floating point it has to be rounded off at some point. Hence when it is converted back to decimal we will get 0.999999 or .1000001 and not 0.1 as we would expect. So comparing floating point numbers for equality wont give the correct results.
But when I printed the numbers it was showing properly!
This is because while printing the numbers they are rounded off and hence we saw the same numbers even though their internal representation varied by a small fraction.
While comparing floating point numbers we will have to test for range and not for equality.
For further details, see What Every Computer Scientist Should Know About Floating-Point Arithmetic (PDF, 240kb)
Originally posted as a Categorized Question.