Passed
Pull Request — master (#138)
by Branko
02:00
created

Euclidean::distance()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2.0185

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 2
dl 0
loc 8
ccs 5
cts 6
cp 0.8333
crap 2.0185
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace OCA\FaceRecognition\Helper;
4
5
class Euclidean
6
{
7
    /**
8
     * Euclidean distance metric between two vectors
9
     *
10
     * The euclidean distance between two vectors (vector1, vector2) is defined as
11
     * D = SQRT(SUM((vector1(i) - vector2(i))^2))  (i = 0..k)
12
     *
13
     * Refs:
14
     * - http://mathworld.wolfram.com/EuclideanMetric.html
15
     * - http://en.wikipedia.org/wiki/Euclidean_distance
16
     *
17
     * @param array $vector1 first vector
18
     * @param array $vector2 second vector
19
     *
20
     * @throws Distance\NonNumericException if vectors are not numeric
21
     * @throws Distance\ImcompatibleItemsException if vectors are of dissimilar size
22
     * @return double The Euclidean distance between vector1 and vector2
23
     * @see _compatibleData()
24
     *
25
     * @assert (array(1,2,3), array(1,2,3,4)) throws Distance\IncompatibleItemsException
26
     * @assert (array(2,'a',6,7), array(4,5,1,9)) throws Distance\NonNumericException
27
     * @assert (array(1,2), array(3,4)) == sqrt(8)
28
     * @assert (array(2,4,6,7), array(4,5,1,9)) == sqrt(4+1+25+4)
29
     *
30
     */
31
32 1
    public function distance($vector1, $vector2)
33
    {
34 1
        $n = count($vector1);
35 1
        $sum = 0;
36 1
        for ($i = 0; $i < $n; $i++) {
37
            $sum += ($vector1[$i] - $vector2[$i]) * ($vector1[$i] - $vector2[$i]);
38
        }
39 1
        return sqrt($sum);
40
    }
41
}
42