Tobias Nawa
Tobias Nawa

Reputation: 55

cannot compare two doubles with PHP

I want to find the shortest distance in my database. $this->tobiMeasure($question, $row["question"]); returns a number, which you can see at the bottom of this post.

$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;

I inserted the print function to check the true values. And here is the problem. The comparison is wrong, but I don't know why.

This is the output of the print function:

0.98151939273405 < 10, 0.98151939273405 < 0.98151939273405, 0 < 0.98151939273405, 0.86200787113796 < 0, 0.89754831644548 < 0.86200787113796, 0.92562573652942 < 0.89754831644548, 1 < 0.92562573652942, 1 < 1, 0.9925897779704 < 1, 1 < 0.9925897779704, 1 < 1, 0.9925897779704 < 1, 0.99433274544623 < 0.9925897779704, 0.9950801111188 < 0.99433274544623, 0.99699990676577 < 0.9950801111188, 0.99699990676577 < 0.99699990676577, 0.9968522683665 < 0.99699990676577, 0.99905782526423 < 0.9968522683665, 0.98744920090422 < 0.99905782526423, 0.98708917521662 < 0.98744920090422, 0.99162758425298 < 0.98708917521662, 1 < 0.99162758425298,

For example the last one. Why is 1 smaller than 0.99...?

Upvotes: 0

Views: 668

Answers (3)

scessor
scessor

Reputation: 16115

You have to remove the ; at the end of this line:

if($compDistance <= $bestDistance);

At the moment it will change every value to the best distance.

Also see the corrected example.

Upvotes: 1

Sabari
Sabari

Reputation: 6335

We can'tt compare floating point numbers (also known as "floats", "doubles", or "real numbers" ) using the == operator.

Floating point numbers have limited precision

We have to check for equality using something like:

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

Hope this helps :)

Upvotes: 0

Layke
Layke

Reputation: 53126

PHP(and any other language) aren't great when comparing numbers with such precision. You should perhaps be looking at using bccomp instead. (I don't know why 1 is smaller than your examples though. That shouldn't be one of the strangeness's that you'd expect to encounter).

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

To take an illustratic example, we as humans can quite easily represent fractal numbers. 1/3 + 1/3 + 1/3 = 1. Try telling that to a computer! That's why you often get strange rounding numbers.

You can always tell if you have a rounding issue by trying to calculate e to the pi Minus pi. </chuckles>

Upvotes: 2

Related Questions