PHP浮点数比较

PHP手册里有一句话:永远不要比较两个浮点数是否相等。php

计算机内部处理浮点数的方式决定了浮点数不可能100%的精确,因此在处理浮点数运算时会出现精度损失问题。好比下面这段程序:html

 

[php] view plaincopyprint?优化

  1. <?php  
  2. $a   =   15521.42;  
  3. $b   =   15480.3;  
  4. $c = $a-$b;  
  5. var_dump($c);    //php4:float(41.120000000001)   php5:float(41.12)   
  6. var_dump($c == 41.12);     //bool(false)   
  7. ?>  

第一条输出语句:在PHP4下输出$c多是41.120000000001,或相似的结果,后面的1就属于精度损失的部分。在PHP5中对这个问题作了些“优化”,输出结果中不会显示不精确的部分,但同时也会让咱们忽视这个问题,觉得$c==41.12。spa

第二条输出语句:在PHP4和PHP5中都会输出false。.net

声明一点:这不是PHP的问题,而是计算机内部处理浮点数的问题!在C/JAVA中也会遇到一样的问题。详细的解释可参看《深刻浅出浮点数htm

延伸一下:咱们一样不能使用>、<、>=或<=blog

那么,咱们应该怎么比较两个浮点数相等呢?ci

看了上面的介绍后,咱们就知道了:没办法精确的比较两个浮点数相等!so..咱们只能在咱们要的精度范围内比较(好比上面的示例,咱们只须要比较$c在小数点后两位内等于41.12便可)。get

下面是PHP手册评论中的示例io

 

[php] view plaincopyprint?

  1. function floatcmp($f1,$f2,$precision = 10) {// are 2 floats equal   
  2.     $e = pow(10,$precision);  
  3.     $i1 = intval($f1 * $e);  
  4.     $i2 = intval($f2 * $e);  
  5.     return ($i1 == $i2);  
  6. }  
  7. function floatgtr($big,$small,$precision = 10) {// is one float bigger than another   
  8.     $e = pow(10,$precision);  
  9.     $ibig = intval($big * $e);  
  10.     $ismall = intval($small * $e);  
  11.     return ($ibig > $ismall);  
  12. }  
  13. function floatgtre($big,$small,$precision = 10) {// is on float bigger or equal to another   
  14.     $e = pow(10,$precision);  
  15.     $ibig = intval($big * $e);  
  16.     $ismall = intval($small * $e);  
  17.     return ($ibig >= $ismall);  
  18. }  
相关文章
相关标签/搜索