I have a function that calculates a value, which is a float:
function crunch (float $a, float $b):float
{
//do stuff
return $result;
}
function testSomething (float $a, float $b):bool
{
//if $result is -0 that returns false
$result = crunch($a, $b);
return $result === 0;
}
Why is -0 not equal to 0 and how can if safely check if that number is zero, assuming that 0
should be the same as -0
?
UPDATE
Since there was the question for more details. I have a class Vec2
which has x()
and y()
getters, and a method called cross
, which looks like that:
public function cross(Vec2 $vec2):float
{
return ($this->_x * $vec2->_y) - ($vec2->_x * $this->_y);
}
Running this code:
$cross = $this->cross($d);
results in that debugger output
and $cross === 0
evaluates to false
;
Cast the 0 to float. It's probably failing because 0 as literal is an int, and the result is a float, so === is false because of types.
At least doing something like this, fails like your case (the result is false):
php -r '$a = (float) -0; $b = 0; echo ($a === $b);'
The result is true in this case:
php -r '$a = (float) -0; $b = (float) 0; echo ($a == $b);'
eg:
function float_equiv(float $a, float $b, float $epsilon=NULL) {
// default to PHP's configured display precision
$epsilon = $epsilon ?: pow(10, -1*ini_get('precision'));
if( abs($a - $b) < $epsilon ) {
return true;
}
return false;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With