Calculate Euclidean distance between 4-dimensional vectors

左心房为你撑大大i 提交于 2019-12-21 04:02:58

问题


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?


回答1:


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 ).




回答2:


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.



来源:https://stackoverflow.com/questions/23353977/calculate-euclidean-distance-between-4-dimensional-vectors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!