Skip to content

Commit 47ee8c9

Browse files
battlecook권욱진battlecook
authored
add euclidean distance and similarity function in vector class (#36)
* add set function in Matrix Class * remove set function in Matrix Class * change namespace and add strict_type in VectorTest class * add magnitude function in Vector Class * add cosine similarity function in vector class * add euclidean distance and similarity function in vector class Co-authored-by: 권욱진 <[email protected]> Co-authored-by: battlecook <[email protected]>
1 parent 2c8a81d commit 47ee8c9

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

src/Vector.php

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,28 @@ public function cosineSimilarity(self $other): float
9797
return $this->dotProduct($other) / ($this->l2Norm() * $other->l2Norm());
9898
}
9999

100+
/**
101+
* @param self $other
102+
* @return float
103+
* @throws VectorException
104+
* @link https://en.wikipedia.org/wiki/Euclidean_distance
105+
*/
106+
public function euclideanDistance(self $other): float
107+
{
108+
return sqrt(array_sum(array_map(
109+
function (float $a, float $b) {
110+
return pow($a - $b, 2);
111+
},
112+
$this->toArray(),
113+
$other->toArray()
114+
)));
115+
}
116+
117+
public function euclideanSimilarity(self $other): float
118+
{
119+
return $this->euclideanDistance($other);
120+
}
121+
100122
/**
101123
* @param self $other
102124
* @return float

tests/VectorTest.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,22 @@ public function testCosineSimilarity()
114114
$this->assertEquals(1.00, $vector1->cosineSimilarity($vector2));
115115
}
116116

117+
public function testEuclideanDistance()
118+
{
119+
$vector1 = new Vector([-1, 2, 3]);
120+
$vector2 = new Vector([4, 0, -3]);
121+
122+
$this->assertEquals(8.06225774829855, $vector1->euclideanDistance($vector2));
123+
}
124+
125+
public function testEuclideanSimilarity()
126+
{
127+
$vector1 = new Vector([-1, 2, 3]);
128+
$vector2 = new Vector([4, 0, -3]);
129+
130+
$this->assertEquals(8.06225774829855, $vector1->euclideanSimilarity($vector2));
131+
}
132+
117133
public function testOuterProduct()
118134
{
119135
$vector1 = new Vector([1, 2]);

0 commit comments

Comments
 (0)