Compare floats in php

后端 未结 16 1995
清歌不尽
清歌不尽 2020-11-22 00:47

I want to compare two floats in PHP, like in this sample code:

$a = 0.17;
$b = 1 - 0.83; //0.17
if($a == $b ){
 echo \'a and b are same\';
}
else {
 echo \'a         


        
16条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 01:42

    Comparing floats for equality has a naive O(n) algorithm.

    You must convert each float value to a string, then compare each digit starting from the left side of each float's string representation using integer comparison operators. PHP will autocast the digit in each index position to an integer before the comparison. The first digit larger than the other will break the loop and declare the float that it belongs to as the greater of the two. On average, there will be 1/2 * n comparisons. For floats equal to each other, there will be n comparisons. This is the worst case scenario for the algorithm. The best case scenario is that the first digit of each float is different, causing only one comparison.

    You cannot use INTEGER COMPARISON OPERATORS on raw float values with the intention of generating useful results. The results of such operations have no meaning because you are not comparing integers. You are violating the domain of each operator which generates meaningless results. This holds for delta comparison as well.

    Use integer comparison operators for what they are designed for : comparing integers.

    SIMPLIFIED SOLUTION:

     $b[$idx]){
       echo "{$a} is greater than {$b}.
    "; break; } else{ echo "{$b} is greater than {$a}.
    "; break; } } ?>

提交回复
热议问题