Skip to content

Instantly share code, notes, and snippets.

@mageekguy
Created August 21, 2012 15:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mageekguy/3416701 to your computer and use it in GitHub Desktop.
Save mageekguy/3416701 to your computer and use it in GitHub Desktop.
public function isNearlyEqualTo($value, $epsilon = null, $failMessage = null)
{
static::check($value, __METHOD__);
// see http://www.floating-point-gui.de/errors/comparison/ for more informations
$originalValue = abs($this->valueIsSet()->value);
$value = abs($value);
$diff = abs($originalValue - $value);
if ($epsilon === null) {
$epsilon = pow(10, - ini_get('precision'));
}
switch (true)
{
case $originalValue == $value:
case $originalValue * $value == 0 && $diff < pow($epsilon, 2):
case $diff / ($originalValue + $value) < $epsilon:
return $this;
default:
$diff = new diffs\variable();
$this->fail(
($failMessage !== null ? $failMessage : sprintf($this->getLocale()->_('%s is not nearly equal to %s with epsilon %s'), $this, $this->getTypeOf($value), $epsilon)) .
PHP_EOL .
$diff->setReference($value)->setData($this->value)
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment