不能用PHP比较两个双打

时间:2012-01-29 10:56:53

标签: php numbers compare

我想在我的数据库中找到最短的距离。 $ this-> tobiMeasure($ question,$ row [“question”]);返回一个数字,您可以在本文的底部看到。

$compDistance = 10.0;
$bestDistance = 10.0;
$bestQuestion = "";

while ($row = $result->fetch_assoc())
{
    $compDistance = $this->tobiMeasure($question, $row["question"]);
    if($compDistance <= $bestDistance);
    {
        print $compDistance." < ".$bestDistance.", ";
        $bestDistance = $compDistance;
        $bestQuestion = $row["question"];
    }
}

$mysqli->close();
return $bestQuestion." : ".$bestDistance;

我插入了print函数来检查真值。这就是问题所在。比较是错误的,但我不知道为什么。

这是打印功能的输出:

0.98151939273405&lt; 10,0.98151939273405&lt; 0.98151939273405,0&lt; 0.98151939273405,0.86200787113796&lt; 0,0.89754831644548&lt; 0.86200787113796,0.92562573652942&lt; 0.89754831644548,1&lt; 0.92562573652942,1&lt; 1,0.9925897779704&lt; 1,1&lt; 0.9925897779704,1&lt; 1,0.9925897779704&lt; 1,0.99433274544623&lt; 0.9925897779704,0.9950801111188&lt; 0.99433274544623,0.99699990676577&lt; 0.9950801111188,0.99699990676577&lt; 0.99699990676577,0.9968522683665&lt; 0.99699990676577,0.99995782526423&lt; 0.9968522683665,0.98744920090422&lt; 0.99905782526423,0.98708917521662&lt; 0.98744920090422,0.99162758425298&lt; 0.98708917521662,1&lt; 0.99162758425298,

例如最后一个。为什么1小于0.99 ......?

3 个答案:

答案 0 :(得分:2)

在比较具有如此精确度的数字时,PHP(和任何其他语言)并不是很好。你或许应该考虑使用bccomp。 (我不知道为什么1比你的例子小。这不应该是你期望遇到的陌生感之一)。

http://www.php.net/manual/en/function.bccomp.php

举一个例证,我们作为人类可以很容易地代表分形数字。 1/3 + 1/3 + 1/3 = 1.尝试告诉计算机!这就是为什么你经常得到奇怪的舍入数字。

您可以通过尝试计算e to the pi Minus pi来判断是否存在舍入问题。 &LT; /笑&GT;

答案 1 :(得分:1)

您必须删除此行末尾的;

if($compDistance <= $bestDistance);

此刻它会将每个值更改为最佳距离。

另见corrected example

答案 2 :(得分:0)

我们无法使用==运算符比较浮点数(也称为“浮点数”,“双数”或“实数”)。

浮点数的精度有限

我们必须使用以下内容检查是否相同:

if(abs($a - $b) < 0.0001) {
    echo "Compared Floats are Equal";
} 

希望这会有所帮助:)