friendship ended with social-app. php is my new best friend
at main 2.2 kB view raw
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 8declare(strict_types=1); 9 10namespace Nette\Utils; 11 12use Nette; 13use function abs, is_finite, is_nan, max, round; 14 15 16/** 17 * Floating-point numbers comparison. 18 */ 19class Floats 20{ 21 use Nette\StaticClass; 22 23 private const Epsilon = 1e-10; 24 25 26 public static function isZero(float $value): bool 27 { 28 return abs($value) < self::Epsilon; 29 } 30 31 32 public static function isInteger(float $value): bool 33 { 34 return abs(round($value) - $value) < self::Epsilon; 35 } 36 37 38 /** 39 * Compare two floats. If $a < $b it returns -1, if they are equal it returns 0 and if $a > $b it returns 1 40 * @throws \LogicException if one of parameters is NAN 41 */ 42 public static function compare(float $a, float $b): int 43 { 44 if (is_nan($a) || is_nan($b)) { 45 throw new \LogicException('Trying to compare NAN'); 46 47 } elseif (!is_finite($a) && !is_finite($b) && $a === $b) { 48 return 0; 49 } 50 51 $diff = abs($a - $b); 52 if (($diff < self::Epsilon || ($diff / max(abs($a), abs($b)) < self::Epsilon))) { 53 return 0; 54 } 55 56 return $a < $b ? -1 : 1; 57 } 58 59 60 /** 61 * Returns true if $a = $b 62 * @throws \LogicException if one of parameters is NAN 63 */ 64 public static function areEqual(float $a, float $b): bool 65 { 66 return self::compare($a, $b) === 0; 67 } 68 69 70 /** 71 * Returns true if $a < $b 72 * @throws \LogicException if one of parameters is NAN 73 */ 74 public static function isLessThan(float $a, float $b): bool 75 { 76 return self::compare($a, $b) < 0; 77 } 78 79 80 /** 81 * Returns true if $a <= $b 82 * @throws \LogicException if one of parameters is NAN 83 */ 84 public static function isLessThanOrEqualTo(float $a, float $b): bool 85 { 86 return self::compare($a, $b) <= 0; 87 } 88 89 90 /** 91 * Returns true if $a > $b 92 * @throws \LogicException if one of parameters is NAN 93 */ 94 public static function isGreaterThan(float $a, float $b): bool 95 { 96 return self::compare($a, $b) > 0; 97 } 98 99 100 /** 101 * Returns true if $a >= $b 102 * @throws \LogicException if one of parameters is NAN 103 */ 104 public static function isGreaterThanOrEqualTo(float $a, float $b): bool 105 { 106 return self::compare($a, $b) >= 0; 107 } 108}