How can i compare 2 floats the right way?
Background: I got a packing tool that packs items into containers.
Whenever i get an object (item, container) into the tool i do cast them to (float)
.
Everything worked fine until i wrote some (more) tests.
The comparison:
$currentContainerHeight + $itemHeight <= $maxContainerHeight
Testoutput:
// actual expected coparison:
1.2345 <= 1.2345
// left === $currentContainerHeight + $itemHeight
// right === $maxContainerHeight
right : 1.2345000000000002
left 1 : 1.1110500000000003
left 2 : 0.12345
left sum : 1.2345000000000004
// "left 1" + "left 2" <= right
1.2345000000000004 <= 1.2345000000000002
Before i go thought all the code and cast the values to (double)
i wanted to ask if this would make sense?
Or how do you handle such a situation the best?
After reading and testing i found out that the most efficient way is to use a leeway|threshold|epsilon.
This may not work the best for everybody but in my case it makes the most sense.
PHP 7.2 comes with PHP_FLOAT_EPSILON
.
I wanna know if
something i will fill up
has still space for
something i want to put in
.
So:
(
$currentContainerHeight + $itemHeight - PHP_FLOAT_EPSILON
) <= $maxContainerHeight
time checks:
$container >= $item - PHP_FLOAT_EPSILON // 0.263153 at 10000000 loops
$container > $item or abs($container - $item) < PHP_FLOAT_EPSILON // 0.538085 at 10000000 loops
bccomp(a, b, 4) >= 0 // 7.643388 at 10000000 loops
sprintf('%f', $container) >= sprintf('%f', $item) // 6.767077 at 10000000 loops