Skip to content

Commit

Permalink
Merge pull request #194 from bizurkur/improve-floating-point-comparison
Browse files Browse the repository at this point in the history
Use epsilon to compare floating points
  • Loading branch information
scaytrase authored Apr 3, 2023
2 parents e69a504 + 333ab35 commit bccdd3f
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 5 deletions.
1 change: 0 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
},
"require": {
"php": ">=7.2",
"ext-bcmath": "*",
"ext-json": "*",
"devizzent/cebe-php-openapi": "^1.0",
"league/uri": "^6.3",
Expand Down
10 changes: 6 additions & 4 deletions src/Schema/Keywords/MultipleOf.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,14 @@
use Respect\Validation\Validator;
use Throwable;

use function bcdiv;
use function class_exists;
use function round;
use function sprintf;

class MultipleOf extends BaseKeyword
{
private const EPSILON = 0.00000001;

/**
* The value of "multipleOf" MUST be a number, strictly greater than 0.
* A numeric instance is only valid if division by this keyword's value results in an integer.
Expand All @@ -39,9 +41,9 @@ public function validate($data, $multipleOf): void
throw InvalidSchema::becauseDefensiveSchemaValidationFailed($e);
}

$value = (float) bcdiv((string) $data, (string) $multipleOf, 1);
if ($value - (int) $value !== 0.0) {
throw KeywordMismatch::fromKeyword('multipleOf', $data, sprintf('Division by %d did not resulted in integer', $multipleOf));
$value = round($data / $multipleOf, 8);
if ($value - (int) $value > self::EPSILON) {
throw KeywordMismatch::fromKeyword('multipleOf', $data, sprintf('Division by %s did not resulted in integer', $multipleOf));
}
}
}
1 change: 1 addition & 0 deletions tests/Schema/Keywords/MultipleOfTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ public function invalidDatasets(): array
[10, .11],
[9.9, .451],
[.94, .03],
[1, .3333333],
];
}

Expand Down

0 comments on commit bccdd3f

Please sign in to comment.