Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.10.x will end 8 November 2021 (12 months).
  • Bug fixes for security issues in 3.10.x will end 9 May 2022 (18 months).
  • PHP version: minimum PHP 7.2.0 Note: minimum PHP version has increased since Moodle 3.8. PHP 7.3.x and 7.4.x are supported too.
   1  <?php
   2  
   3  declare(strict_types=1);
   4  
   5  namespace Phpml\Math\Distance;
   6  
   7  use Phpml\Exception\InvalidArgumentException;
   8  use Phpml\Math\Distance as DistanceInterface;
   9  
  10  /**
  11   * Class Distance
  12   */
  13  abstract class Distance implements DistanceInterface
  14  {
  15      /**
  16       * @var float|int
  17       */
  18      public $norm;
  19  
  20      /**
  21       * Distance constructor.
  22       */
  23      public function __construct(float $norm = 3.0)
  24      {
  25          $this->norm = $norm;
  26      }
  27  
  28      /**
  29       * @throws InvalidArgumentException
  30       */
  31      public function distance(array $a, array $b): float
  32      {
  33          $distance = 0;
  34  
  35          foreach ($this->deltas($a, $b) as $delta) {
  36              $distance += $delta ** $this->norm;
  37          }
  38  
  39          return $distance ** (1 / $this->norm);
  40      }
  41  
  42      /**
  43       * @throws InvalidArgumentException
  44       */
  45      protected function deltas(array $a, array $b): array
  46      {
  47          $count = count($a);
  48  
  49          if ($count !== count($b)) {
  50              throw new InvalidArgumentException('Size of given arrays does not match');
  51          }
  52  
  53          $deltas = [];
  54  
  55          for ($i = 0; $i < $count; $i++) {
  56              $deltas[] = abs($a[$i] - $b[$i]);
  57          }
  58  
  59          return $deltas;
  60      }
  61  }