note 47841 added to language.operators.comparison
| From: | php-general at lists dot php dot net | Date: | Thu, 02 Dec 2004 11:47:19 +0000 |
| Subject: | note 47841 added to language.operators.comparison | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-81269@lists.php.net to get a copy of this message | ||
Concerning floats: It is simply pointless to compare a float with the value "0.3". The
number 0.3 is not exactly representable in binary. Period. So is the number 0.1, and an infinite
number of others numbers. Just like 1/3 is not exactly representable in decimal. How would you code
the test for your float to be one third? Maybe $myFloat == 0.33333333333 Hmm: you see: Everyone
would agree that this test is not accurate.
The test $myFloat == 0.3 is making exactly the same mistake.
So the float which you think should be 0.3 is really something very close to it; if you print it in
decimal, the conversion will end up with the closest decimal representation, which may well be
"0.3". But "0.3" is also the "right display decimal" for hundreds of
float values.
The correct way to "compare" floats is: ( $myFloat - 0.3 ) < $EPSILON where $EPSILON is
something like 1e-10, depending on your application. Approximate algorithms are the only right way
to treat floats, which are only approximate by themselves.
----
Manual Page -- http://www.php.net/manual/en/language.operators.comparison.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+47841
Delete -- http://master.php.net/manage/user-notes.php?action=delete+47841&report=yes
Reason: bad code -- http://master.php.net/manage/user-notes.php?action=delete+47841&report=yes&reason=bad+code
Reason: spam -- http://master.php.net/manage/user-notes.php?action=delete+47841&report=yes&reason=spam
Reason: useless example -- http://master.php.net/manage/user-notes.php?action=delete+47841&report=yes&reason=useless+example
Reason: contains commercial links -- http://master.php.net/manage/user-notes.php?action=delete+47841&report=yes&reason=contains+commercial+links
Reason: useless note -- http://master.php.net/manage/user-notes.php?action=delete+47841&report=yes&reason=useless+note
Reject -- http://master.php.net/manage/user-notes.php?action=reject+47841&report=yes
Search -- http://master.php.net/manage/user-notes.php