PHP 函数 'pow' 奇怪的结果

PHP function 'pow' weird result

我正在编写代码,但我无法理解我得到的奇怪结果。

<?php

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

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

?>

这个条件的结果总是 "true" 而两个变量具有相同的值,但是来自 pow 的结果在内部改变了一些东西。好像我不能依赖这个功能。有人可以帮我解决这个问题吗?

PHP 文档说:

base raised to the power of exp. If both arguments are non-negative integers and the result can be represented as an integer, the result will be returned with integer type, otherwise it will be returned as a float.

也许您需要将全部转换为 int 或全部转换为 float。

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

看到了运行:

http://phpfiddle.org/main/code/2hv5-n2fw

这是因为浮动不准确, 看看 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)

因此您可以信任 pow 函数,但不能信任浮点数比较