Completed
Pull Request — master (#13)
by Benjamin
02:12
created

EuclidianDistance::getDistanceBetween()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 20
rs 9.6
c 0
b 0
f 0
cc 3
nc 3
nop 2
1
<?php
2
3
namespace KMeans\Algorithms;
4
5
use KMeans\Interfaces\DistanceAlgorithmInterface;
6
use KMeans\Interfaces\PointInterface;
7
8
class EuclidianDistance implements DistanceAlgorithmInterface
9
{
10
    public function getDistanceBetween(PointInterface $pointA, PointInterface $pointB): float
11
    {
12
        if ($pointA->getSpace()->getDimention() !== $pointB->getSpace()->getDimention()) {
13
            throw new \LogicException(
14
                "Cannot calculate euclidian distance between point of different dimentions"
15
            );
16
        }
17
18
        $distance = 0;
19
        $dimention = $pointA->getSpace()->getDimention();
20
        $coordinatesA = $pointA->getCoordinates();
21
        $coordinatesB = $pointB->getCoordinates();
22
23
        for ($n = 0; $n < $dimention; $n++) {
24
            $difference = $coordinatesA[$n] - $coordinatesB[$n];
25
            $distance += $difference ** 2;
26
        }
27
28
        return sqrt($distance);
29
    }
30
}
31