| 1 |
<?php |
| 2 |
|
| 3 |
/** |
| 4 |
* This file is part of the Nette Framework (https://nette.org) |
| 5 |
* Copyright (c) 2004 David Grudl (https://davidgrudl.com) |
| 6 |
*/ |
| 7 |
declare (strict_types=1); |
| 8 |
namespace Packetery\Nette\Utils; |
| 9 |
|
| 10 |
use Packetery\Nette; |
| 11 |
/** |
| 12 |
* Floating-point numbers comparison. |
| 13 |
*/ |
| 14 |
class Floats |
| 15 |
{ |
| 16 |
use \Packetery\Nette\StaticClass; |
| 17 |
private const Epsilon = 1.0E-10; |
| 18 |
public static function isZero(float $value) : bool |
| 19 |
{ |
| 20 |
return \abs($value) < self::Epsilon; |
| 21 |
} |
| 22 |
public static function isInteger(float $value) : bool |
| 23 |
{ |
| 24 |
return \abs(\round($value) - $value) < self::Epsilon; |
| 25 |
} |
| 26 |
/** |
| 27 |
* Compare two floats. If $a < $b it returns -1, if they are equal it returns 0 and if $a > $b it returns 1 |
| 28 |
* @throws \LogicException if one of parameters is NAN |
| 29 |
*/ |
| 30 |
public static function compare(float $a, float $b) : int |
| 31 |
{ |
| 32 |
if (\is_nan($a) || \is_nan($b)) { |
| 33 |
throw new \LogicException('Trying to compare NAN'); |
| 34 |
} elseif (!\is_finite($a) && !\is_finite($b) && $a === $b) { |
| 35 |
return 0; |
| 36 |
} |
| 37 |
$diff = \abs($a - $b); |
| 38 |
if ($diff < self::Epsilon || $diff / \max(\abs($a), \abs($b)) < self::Epsilon) { |
| 39 |
return 0; |
| 40 |
} |
| 41 |
return $a < $b ? -1 : 1; |
| 42 |
} |
| 43 |
/** |
| 44 |
* Returns true if $a = $b |
| 45 |
* @throws \LogicException if one of parameters is NAN |
| 46 |
*/ |
| 47 |
public static function areEqual(float $a, float $b) : bool |
| 48 |
{ |
| 49 |
return self::compare($a, $b) === 0; |
| 50 |
} |
| 51 |
/** |
| 52 |
* Returns true if $a < $b |
| 53 |
* @throws \LogicException if one of parameters is NAN |
| 54 |
*/ |
| 55 |
public static function isLessThan(float $a, float $b) : bool |
| 56 |
{ |
| 57 |
return self::compare($a, $b) < 0; |
| 58 |
} |
| 59 |
/** |
| 60 |
* Returns true if $a <= $b |
| 61 |
* @throws \LogicException if one of parameters is NAN |
| 62 |
*/ |
| 63 |
public static function isLessThanOrEqualTo(float $a, float $b) : bool |
| 64 |
{ |
| 65 |
return self::compare($a, $b) <= 0; |
| 66 |
} |
| 67 |
/** |
| 68 |
* Returns true if $a > $b |
| 69 |
* @throws \LogicException if one of parameters is NAN |
| 70 |
*/ |
| 71 |
public static function isGreaterThan(float $a, float $b) : bool |
| 72 |
{ |
| 73 |
return self::compare($a, $b) > 0; |
| 74 |
} |
| 75 |
/** |
| 76 |
* Returns true if $a >= $b |
| 77 |
* @throws \LogicException if one of parameters is NAN |
| 78 |
*/ |
| 79 |
public static function isGreaterThanOrEqualTo(float $a, float $b) : bool |
| 80 |
{ |
| 81 |
return self::compare($a, $b) >= 0; |
| 82 |
} |
| 83 |
} |
| 84 |
|