Skip to content

Commit

Permalink
Use smaller epsilon and relative error for float comparison (#1570)
Browse files Browse the repository at this point in the history
Fixes #1537
  • Loading branch information
sanmai committed Sep 11, 2021
1 parent 77b684a commit 5c18760
Showing 1 changed file with 24 additions and 1 deletion.
Expand Up @@ -59,6 +59,13 @@
*/
final class TestLocationBucketSorterTest extends TestCase
{
/**
* Used for floating point comparisons.
*
* @var float
*/
private const EPSILON = 0.001;

public function test_it_sorts(): void
{
$testLocation = new TestLocation('', '', 0.0);
Expand Down Expand Up @@ -189,7 +196,7 @@ public function test_it_sorts_faster_than_quicksort(ArrayIterator $uniqueTestLoc
$totalQuickSort += microtime(true) - $start;
}

$this->assertGreaterThanOrEqual(0.01, abs($totalQuickSort - $totalBucketSort));
$this->assertGreaterThanOrEqual(self::EPSILON, self::getRelativeError($totalQuickSort, $totalBucketSort));
}

public static function locationsArrayProvider(): iterable
Expand All @@ -206,6 +213,22 @@ static function (float $executionTime): TestLocation {
yield 'All locations' => [new ArrayIterator($locations)];
}

/**
* Finds relative error.
*
* @see https://floating-point-gui.de/errors/comparison/
* @see https://stackoverflow.com/questions/4915462/how-should-i-do-floating-point-comparison
*/
private static function getRelativeError(float $a, float $b): float
{
// We do not expect A or B to be extremely small or large: these are edge cases,
// and they will need special handling which we avoid simplicity sake.
self::assertGreaterThan(self::EPSILON, abs($a));
self::assertGreaterThan(self::EPSILON, abs($b));

return abs($a - $b) / (abs($a) + abs($b));
}

private static function quicksort(&$uniqueTestLocations): void
{
usort(
Expand Down

0 comments on commit 5c18760

Please sign in to comment.