Reputation: 267
I have two 3-D points.
Example:
float[] point1 = new float[3] {1.3919023, 6.12837912, 10.391283};
float[] point2 = new float[3] {48.3818, 38.38182, 318.381823};
Anyone an idea for an algorithm to calculate the distance in float between the points?
Upvotes: 8
Views: 21409
Reputation: 727067
In C# with LINQ you can do this:
var dist = Math.Sqrt(point1.Zip(point2, (a, b) => (a - b)*(a - b)).Sum());
This sums up squared pairwise differences between individual coordinates, and returns the arithmetic square root of the sum.
EDIT : This solution works for any number of dimensions greater or equal to one (thanks to Austin Salonen for pointing it out).
Upvotes: 21
Reputation: 10074
The Euclidean distance between two 3D points is:
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 much prefer the Zip
solution posted by dasblinkenlight below!
Upvotes: 26
Reputation: 12735
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))
Upvotes: 10
Reputation: 57593
If you have two points:
P1 = (x1, y1, z1)
P2 = (x2, y2, z2)
distance is SQRT((x2-x1)^2 + (y2-y1)^2 + (z2-z1)^2)
So you could 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));
Upvotes: 2
Reputation: 32790
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 down in C# but you get the idea.
Upvotes: 4