Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating the distance between 2 points

Tags:

c#

I have two points (x1,y1) and (x2,y2). I want to know whether the points are within 5 meters of one another.

like image 641
user1307376 Avatar asked Jul 19 '12 06:07

user1307376


2 Answers

If you are using System.Windows.Point data type to represent a point, you can use

// assuming p1 and p2 data types
Point p1, p2;
// distanc can be calculated as follows
double distance = Point.Subtract(p2, p1).Length;

Update 2017-01-08:

  • Add reference to Microsoft documentation
  • Result of Point.Subtract is System.Windows.Vector and it has also property LengthSquared to save one sqrt calculation if you just need to compare distance.
  • Adding reference to WindowsBase assembly may be needed in your project
  • You can also use operators

Example with LengthSquared and operators

// assuming p1 and p2 data types
Point p1, p2;
// distanc can be calculated as follows
double distanceSquared = (p2 - p1).LengthSquared;

Update 2021-11-15:

Unfortunately, System.Windows.Point and WindowsBase is available only in .Net Framework. It is not part of .NET, .NET standard, .NET core.

System.Drawing.Point and System.Drawing.PointF does not have any usable methods and operators and they are just containers.

Interesing is System.Numerics.Vector2 which is probably best replacement for System.Windows.Point. It has similar API and is available in all .NET flawors. But, the semantics is strange - using Vector for Point representation.

like image 70
j123b567 Avatar answered Sep 20 '22 19:09

j123b567


measure the square distance from one point to the other:

((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)) < d*d

where d is the distance, (x1,y1) are the coordinates of the 'base point' and (x2,y2) the coordinates of the point you want to check.

or if you prefer:

(Math.Pow(x1-x2,2)+Math.Pow(y1-y2,2)) < (d*d);

Noticed that the preferred one does not call Pow at all for speed reasons, and the second one, probably slower, as well does not call Math.Sqrt, always for performance reasons. Maybe such optimization are premature in your case, but they are useful if that code has to be executed a lot of times.

Of course you are talking in meters and I supposed point coordinates are expressed in meters too.

like image 44
Felice Pollano Avatar answered Sep 20 '22 19:09

Felice Pollano