19

Let's say I have two 4-dimensional vectors (i.e. a and b) as follows:

a = {a1, a2, a3, a4}
b= {b1, b2, b3, b4}

How do I compute the Euclidean distance between these vectors?

Has QUIT--Anony-Mousse
  • 76,138
  • 12
  • 138
  • 194
user3583442
  • 209
  • 1
  • 2
  • 4
  • 4
    Same as for a 2D or 3D vector. You just [keep adding](http://en.wikipedia.org/wiki/Euclidean_distance#N_dimensions) ``+(a-b)^2`` terms to the ``sqrt``. I.E. ``sqrt((a1-b1)^2+(a2-b2)^2...)`` – aruisdante Apr 29 '14 at 01:33
  • 1
    I'm voting to close this question as off-topic because it is about math, not programming. – Robert Columbia Oct 29 '17 at 13:51
  • 1
    I'm voting to close this question as off-topic because it is about [math.se] instead of programming or software development. – Pang Oct 31 '17 at 01:21

3 Answers3

32

The euclidian distance calculus is independent of dimensions.

In your case, the euclidian distance between a and b can be written as:

d(a,b) = sqrt( sum_{ i=1 } ^ { 4 } (a[ i ] - b[ i ])^2 )

Or, more specifically:

d(a,b) = sqrt( (a1 - b1)^2 + (a2 - b2)^2 + (a3 -b3)^2 + (a4 - b4)^2 )
Dhruvin modi
  • 613
  • 1
  • 8
  • 13
7
public static float ndistance(float[] a, float[] b) {
    float total = 0, diff;
    for (int i = 0; i < a.length; i++) {
        diff = b[i] - a[i];
        total += diff * diff;
    }
    return (float) Math.sqrt(total);
}

The function/method/code above will calculate the distance in n-dimensional space. a and b are arrays of floating point number and have the same length/size or simply the n. Since you want a 4-dimension, you simply pass a 4-length array representing the data of your 4-D vector.

D.R.Bendanillo
  • 307
  • 4
  • 7
0

Old questions but I thought I'd share a one liner:

import numpy as np
from functools import reduce

def euclidean_distance(arr: np.ndarray):
    """
        d = √((x₂ - x₁)² + (y₂ - y₁)² + (z₂ - z₁)² + ... + (xn₂ - xn₁)²)
    """
    return np.sqrt(sum(np.power(reduce(np.subtract, arr), 2)))
Isma
  • 14,604
  • 5
  • 37
  • 51