Calculate a squared Euclidean distance

Preserve the order of coordinates and the signs of values. · 160 words

Squared Euclidean distance compares two vectors by subtracting corresponding entries, squaring each difference, and adding the results. It is the square of the ordinary straight-line distance. A k-nearest-neighbor model, which predicts from nearby examples, uses this measure. For an online shop, let a customer's desired vector be (2,1), meaning price 2 units and delivery time 1 day. Compare offers (4,1) and (1,3). The first squared distance is (2-4)^2+(1-1)^2=4. The second is (2-1)^2+(1-3)^2=5. Therefore the first offer is nearer. In a feature matrix, these vectors can be rows or query and candidate columns.

A color-matching system gives a second example. Compare pixel vectors (255,0,0) and (250,10,5), with entries for red, green, and blue. Their squared Euclidean distance is (255-250)^2+(0-10)^2+(0-5)^2=150. A smaller value means a closer color match, so an image filter can rank several patches with this score. If ordinary distance were needed, it would be sqrt(150), about 12.25. The squared version avoids a square root and preserves the same ordering.

Check your recall

What is the squared Euclidean distance between (3,4) and (1,2), and how does it relate to ordinary distance?

Check your answer

Subtract corresponding entries, square, and add: (3-1)^2+(4-2)^2=4+4=8. The ordinary distance is sqrt(8), approximately 2.83.

Sources and credits

Original KeyTouch lesson. Background reading · Zhang et al. · Linear Algebra.