note 119860 added to language.types.float
| From: | Eduard | Date: | Wed, 07 Sep 2016 14:23:38 +0000 |
| Subject: | note 119860 added to language.types.float | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-206521@lists.php.net to get a copy of this message | ||
In the gettype() manual, it says "(for historical reasons "double" is returned in
case of a float, and not simply "float") ".
However, I think that internally PHP sometimes uses the C double definition (i.e. a double is twice
the size of a float/real). See the example below:
<?
//Function required to reverse a string on blocks of two
function strrev_x($s, $x = 2) {
if ($x <= 1) {
return strrev($s);
} else {
return (implode(array_reverse(array_map('implode', array_chunk(str_split($s), $x)))));
}
}
echo 'double pack'. PHP_EOL;
$tst = pack('d', '1.6');
var_dump(strrev_x(bin2hex($tst)));
$tst = pack('d', 8-6.4);
var_dump(strrev_x(bin2hex($tst)));
echo 'float pack'. PHP_EOL;
$tst = pack('f', '1.6');
var_dump(strrev_x(bin2hex($tst)));
$tst = pack('f', 8-6.4);
var_dump(strrev_x(bin2hex($tst)));
?>
(The strrev_x-bin2hex combination is just to give printable characters.)
Given that PHP treats doubles and floats identically, I'd expected the same string as output,
however, the output is:
double pack
string(16) "3ff999999999999a" //Here you see that there is a minute difference...
string(16) "3ff9999999999998"
float pack
string(8) "3fcccccd" //... which doesn't exist here
string(8) "3fcccccd"
So, as an alternative to using
$float1 === $float2
one could use
pack('f', $float1) === pack ('f', $float2)
with a big footnote that one should really remember that one is *reducing* your accuracy of the
comparison. AFAIK is this the only way (apart from epsilon methods) to securely compare two floats.
----
Server IP: 72.52.91.14
Probable Submitter: 31.161.105.18
----
Manual Page -- http://php.net/manual/en/language.types.float.php
Edit -- https://master.php.net/note/edit/119860
Del: integrated -- https://master.php.net/note/delete/119860/integrated
Del: useless -- https://master.php.net/note/delete/119860/useless
Del: bad code -- https://master.php.net/note/delete/119860/bad+code
Del: spam -- https://master.php.net/note/delete/119860/spam
Del: non-english -- https://master.php.net/note/delete/119860/non-english
Del: in docs -- https://master.php.net/note/delete/119860/in+docs
Del: other reasons-- https://master.php.net/note/delete/119860
Reject -- https://master.php.net/note/reject/119860
Search -- https://master.php.net/manage/user-notes.php