关于浮点数比较,手册没看清楚

WBOY
Release: 2016-06-13 12:22:20
Original
970 people have browsed it

关于浮点数比较,手册没看明白;
$a = 1.11;
$b = 1.11;

if($a==$b){
//结果是真啊;
}

不是说永远不要比较两个浮点数是否相等吗?
其意思到底是什么, 是计算过后的浮点数不能比较吗? 
------解决思路----------------------
不是说不要比较,而是说由于精度的原因,看似相同的俩个数,比较起来并不相等
你比较两个相同精度的数,当然是没有问题的


------解决思路----------------------
不是不能比较,只是不准确而已。

例如:

<br />$a = 1.1000000000000000001;<br />$b = 1.1000000000000000011;<br /><br />if($a==$b){<br />    echo 'equal';<br />}else{<br />    echo 'not equal';<br />}<br />
Copy after login


输出equal
------解决思路----------------------
$a = 1.00000000000000001;<br />$b = 1.00000000000000002;<br />var_dump($a == $b); //bool(true) 居然是相等的<br /><br />$s = pack('f', $a);<br />for($i=0; $i<strlen($s); $i++) printf(' %08b', ord($s{$i}));<br />echo PHP_EOL;<br /><br />$s = pack('f', $b);<br />for($i=0; $i<strlen($s); $i++) printf(' %08b', ord($s{$i}));<br />echo PHP_EOL;<br />
Copy after login

原来他们在计算机中保存时就一样了
 00000000 00000000 10000000 00111111
 00000000 00000000 10000000 00111111

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template