I have two points (x1,y1) and (x2,y2). I want to know whether the points are within 5 meters of one another.
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:
Point.Subtract
is System.Windows.Vector and it has also property LengthSquared
to save one sqrt
calculation if you just need to compare distance.WindowsBase
assembly may be needed in your projectExample 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With