Algorithm for calculating the distance between 2 3-dimensional points?

I have two 3 points.
Example:

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

Any idea for an algorithm to calculate the distance in a float between points?

+7
source share
5 answers

Euclidean distance between two three-dimensional points:

 float deltaX = x1 - x0; float deltaY = y1 - y0; float deltaZ = z1 - z0; float distance = (float) Math.Sqrt(deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ); 

And in N dimensions (untested and vulnerable to overflow):

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

Edit: I prefer the Zip solution posted by dasblinkenlight below!

+21
source

In C # with LINQ, you can do this:

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

This summarizes the quadratic pairwise differences between the individual coordinates and returns the square root of arithmetic from the sum.

EDIT: This solution works for any number of dimensions greater than or equal to one (thanks to Austin Salonen for pointing out).

+16
source

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

+10
source

Like 2D, but with one more coordinate:

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

Obviously not written in C #, but you get the idea.

+4
source

If you have two points:
P1 = (x1, y1, z1)
P2 = (x2, y2, z2)
distance SQRT((x2-x1)^2 + (y2-y1)^2 + (z2-z1)^2)

So you can use

 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)); 
+2
source

All Articles