Distance.php 1.15 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<?php

declare(strict_types=1);

namespace Phpml\Math\Distance;

use Phpml\Exception\InvalidArgumentException;
use Phpml\Math\Distance as DistanceInterface;

/**
 * Class Distance
 */
abstract class Distance implements DistanceInterface
{
    /**
     * @var float|int
     */
    public $norm;

    /**
     * Distance constructor.
     */
    public function __construct(float $norm = 3.0)
    {
        $this->norm = $norm;
    }

    /**
     * @throws InvalidArgumentException
     */
    public function distance(array $a, array $b): float
    {
        $distance = 0;

        foreach ($this->deltas($a, $b) as $delta) {
            $distance += $delta ** $this->norm;
        }

        return $distance ** (1 / $this->norm);
    }

    /**
     * @throws InvalidArgumentException
     */
    protected function deltas(array $a, array $b): array
    {
        $count = count($a);

        if ($count !== count($b)) {
            throw new InvalidArgumentException('Size of given arrays does not match');
        }

        $deltas = [];

        for ($i = 0; $i < $count; $i++) {
            $deltas[] = abs($a[$i] - $b[$i]);
        }

        return $deltas;
    }
}