Euclidean distance, dot product, cosine similarity
Examples of using Euclidean distance, dot product, and cosine similarity.
Below is a minimal runnable example for all three operations with explicit input vectors and interpretation of results.
Example of use
<?php
require_once __DIR__ . '/code.php';
echo 'Example 1: Euclidean distance' . PHP_EOL . '----------' . PHP_EOL;
$a = [1, 2, 3];
$b = [4, 6, 3];
echo 'a: ' . array_to_vector($a) . PHP_EOL;
echo 'b: ' . array_to_vector($b) . PHP_EOL . PHP_EOL;
$distance = euclideanDistance($a, $b);
echo 'Euclidean distance: ' . $distance . PHP_EOL;
echo 'Explanation: sqrt((1 - 4)^2 + (2 - 6)^2 + (3 - 3)^2) = sqrt(9 + 16 + 0) = sqrt(25) = 5' . PHP_EOL . PHP_EOL;
echo 'Example 2: Dot product' . PHP_EOL . '----------' . PHP_EOL;
$a = [1, 2, 3];
$b = [4, 5, 6];
echo 'a: ' . array_to_vector($a) . PHP_EOL;
echo 'b: ' . array_to_vector($b) . PHP_EOL . PHP_EOL;
$result = dotProduct($a, $b);
echo 'Dot product: ' . $result . PHP_EOL;
echo 'Explanation: (1 * 4) + (2 * 5) + (3 * 6) = 4 + 10 + 18 = 32' . PHP_EOL . PHP_EOL;
echo 'Example 3: Cosine similarity' . PHP_EOL . '----------' . PHP_EOL;
$a = [1, 2];
$b = [2, 1];
echo 'a: ' . array_to_vector($a) . PHP_EOL;
echo 'b: ' . array_to_vector($b) . PHP_EOL . PHP_EOL;
$similarity = cosineSimilarity($a, $b);
echo 'Cosine similarity: ' . $similarity . PHP_EOL;
echo 'Explanation:' . PHP_EOL;
echo 'dot = 1 * 2 + 2 * 1 = 4' . PHP_EOL;
echo 'normA = sqrt(1 * 1 + 2 * 2) = sqrt(5)' . PHP_EOL;
echo 'normB = sqrt(2 * 2 + 1 * 1) = sqrt(5)' . PHP_EOL;
echo 'cosine = 4 / (sqrt(5) * sqrt(5)) = 4 / 5 = 0.8';
Result:
Memory: 0.007 Mb
Time running: 0.001 sec.
Example 1: Euclidean distance
----------
a: [1, 2, 3]
b: [4, 6, 3]
Euclidean distance: 5
Explanation: sqrt((1 - 4)^2 + (2 - 6)^2 + (3 - 3)^2) = sqrt(9 + 16 + 0) = sqrt(25) = 5
Example 2: Dot product
----------
a: [1, 2, 3]
b: [4, 5, 6]
Dot product: 32
Explanation: (1 * 4) + (2 * 5) + (3 * 6) = 4 + 10 + 18 = 32
Example 3: Cosine similarity
----------
a: [1, 2]
b: [2, 1]
Cosine similarity: 0.8
Explanation:
dot = 1 * 2 + 2 * 1 = 4
normA = sqrt(1 * 1 + 2 * 2) = sqrt(5)
normB = sqrt(2 * 2 + 1 * 1) = sqrt(5)
cosine = 4 / (sqrt(5) * sqrt(5)) = 4 / 5 = 0.8
The key takeaway: choose the metric based on task semantics. Distance is about absolute difference, dot product is about weighted alignment, and cosine similarity is about angle and direction.