2012-01-18 284 views
7

我有兩個3-D點。
實施例:計算2個三維點之間距離的算法?

float[] point1 = new float[3] {1.3919023, 6.12837912, 10.391283}; 
float[] point2 = new float[3] {48.3818, 38.38182, 318.381823}; 

任何一個算法來計算在這些點之間浮動的距離的想法?

+14

我們會讓你儘快維基百科的停電結束認識。 – Nathan

+2

如果社區無法在不使用谷歌搜索的情況下回答這個問題,那麼這個世界就註定要失敗。這讓我想起:你爲什麼不穀歌這個? – Jon

回答

21

兩個3D點之間的歐幾里得距離:

float deltaX = x1 - x0; 
float deltaY = y1 - y0; 
float deltaZ = z1 - z0; 

float distance = (float) Math.Sqrt(deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ); 

而在N個維度(未經測試和易受溢出):

float DistanceN(float[] first, float[] second) { 
    var sum = first.Select((x, i) => (x - second[i]) * (x - second[i])).Sum(); 
    return Math.Sqrt(sum); 
} 

編輯:我更喜歡Zip溶液貼通過下面的dasblinkenlight!

+0

你的意思是delta x平方向右? –

+0

謝謝,先生。 – Headpuster

+0

@JohnBoker:固定,謝謝。另外這個問題已經被問了很多次在這裏... ... –

4

像2D但有一個更協調:

P1(x1, y1, z1); P2(x2, y2, z2) 

d = SquareRootOf((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2) + (z1-z2)*(z1-z2)); 

顯然不是在C#寫下來,但你的想法。

2

如果您有兩點:
P1 =(X1,Y1,Z1)
P2 =(X2,Y2,Z2)
距離爲SQRT((x2-x1)^2 + (y2-y1)^2 + (z2-z1)^2)

所以,你可以使用

float deltax = point2[0] - point1[0]; 
float deltay = point2[1] - point1[1]; 
float deltaz = point2[2] - point1[2]; 
float distance = (float) Math.Sqrt(
    (deltax * deltax) + 
    (deltay * deltay) + 
    (deltaz * deltaz)); 
16

在C#中使用LINQ,你可以這樣做:

var dist = Math.Sqrt(point1.Zip(point2, (a, b) => (a - b)*(a - b)).Sum()); 

釷將各個座標之間的平方成對差值相加,並返回總和的算術平方根。

編輯:該解決方案適用於任何數量的維度大於或等於1(感謝Austin Salonen指出)。

+0

非常好的n維解決方案 –

+0

這看起來很棒單行:D你測試,以驗證它的工作與否? – MonsterMMORPG

+0

@MonsterMMORPG當「point1」和「point2」的大小匹配時,除了產生平方成對差之和的平方根外沒有別的選擇:-) – dasblinkenlight

10

enter image description here

float distance=(float) Math.Sqrt(Math.Pow(point1[0]-point2[0],2) + Math.Pow(point1[1]-point2[1],2) + Math.Pow(point1[2]-point2[2],2))