float php 运算_PHP: Float 浮点型 - Manual

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值