Bug #17282 Updated: Identical float values are not identical when compared

From: Date: Fri, 17 May 2002 06:41:24 +0000
Subject: Bug #17282 Updated: Identical float values are not identical when compared
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-7898@lists.php.net to get a copy of this message
ID: 17282 Updated by: derick@php.net Reported By: david@acz.org Status: Bogus Bug Type: Scripting Engine problem Operating System: FreeBSD 4.4-STABLE PHP Version: 4.2.1 New Comment: Actually this is documented: http://www.php.net/manual/en/language.types.float.php > I am well aware that there can be errors due to loss of precision, but > in that case, the number should not appear to be _exactly the same_. > There should be some way to tell that they are different. You can tell they are different by comparing them, which obviously almost always fails, but i fyou do this: if (41.96 == 41.96) it will return true ofcourse. There was some discussion on this topic before, and the consensus of the list was not to change anything related to this. regards, Derick Previous Comments: ------------------------------------------------------------------------ [2002-05-17 02:36:19] david@acz.org That does not seem right. The numbers appear to be exactly the same. Even if they can't be compared as floats, comparing untyped should work, because they look exactly the same (when var_dump'd and printed). Even if this is in fact bogus, it needs to be documented. I am well aware that there can be errors due to loss of precision, but in that case, the number should not appear to be _exactly the same_. There should be some way to tell that they are different. ------------------------------------------------------------------------ [2002-05-17 02:16:22] derick@php.net You can't compare floats like this, a float is an approximation of the number, but never exact the number. This is not a bug, this wouldn't work in most languages, including C -> Bogus ------------------------------------------------------------------------ [2002-05-16 22:23:02] david@acz.org This problem also occurs on PHP 4.1.2. The following code fragment produces very odd results: <? $a = array(41.96, 20.97, 20.99); $t = 0; for($i = 1; $i < count($a); $i++) $t += abs($a[$i]); echo "$t != $a[0]\n"; var_dump($t != $a[0]); echo "t = "; var_dump($t); echo "a[0] = "; var_dump($a[0]); ?> The results are shown below: 41.96 != 41.96 bool(true) t = float(41.96) a[0] = float(41.96) Both variables appear to be the same type, and look the same, yet compare incorrectly with both typed and untyped comparisons. ------------------------------------------------------------------------ -- Edit this bug report at http://bugs.php.net/?id=17282&edit=1

« previous php.bugs (#7898) next »