Search code examples
phpif-statementpow

PHP function 'pow' weird result


I was working on a code and I could not understand the weird result I was getting.

<?php

    $a = 0.01;  
    $p = pow(0.1, 2); // result: 0.01

    if( $a < $p ){
        echo "true";
    }

?>

The result of this condition is always "true" while both of the variables have same value, but the result coming from pow is changing something internally. Seems like I would not be able to rely on this function. Would someone please help me figuring this out ?


Solution

  • its because of float inaccuracy, take a look at answered question mentioned in comment by b0s3

    Read the red warning first http://www.php.net/manual/en/language.types.float.php. You must never compare floats for equality. You should use the epsilon technique.

    For example:

    if (abs($a-$b) < EPSILON) { … } where EPSILON is constant representing a very small number (you have to define it)

    https://stackoverflow.com/a/3149007/4998045

    so you can trust pow function but you cant trust float comparsion