18

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

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
user1307376
  • 321
  • 1
  • 2
  • 7
  • 3
    possible duplicate of [Distance between 2 points](http://stackoverflow.com/questions/6182005/distance-between-2-points) – H H Jul 19 '12 at 06:55
  • Having a language specific version of this question is useful. Though the question body and title are in disagreement. The accepted solution does not "calculate the distance between 2 points" so maybe the title should be updated. It was a title added by an editor also. – AnnanFay Sep 12 '20 at 17:20

10 Answers10

59

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.

j123b567
  • 3,110
  • 1
  • 23
  • 32
  • 5
    There is no `System.Windows.Point` type, it is `System.Drawing.Point`. There is also no overload of `Subtract` that takes two points, the second argument must be a `Size`. – Dave Cousineau Jan 06 '17 at 22:21
  • 5
    @Sahuagin There is [System.Windows.Point](https://msdn.microsoft.com/en-us/library/system.windows.point(v=vs.110).aspx)! You just need to reference WindowsBase assambly in your project. – j123b567 Jan 08 '17 at 08:02
  • @Sahuagin There is also problem that `System.Drawing.Point` is just `int32` based. There is also `single` based `System.Drawing.PointF` but none of them has such functionality like `.Length` field. – j123b567 Jan 08 '17 at 08:15
  • if you can't see it, then the project doesn't have required assembly, use project add references WindowsBase – YEH Dec 27 '18 at 02:35
  • 1
    Note that if you are using `System.Drawing.Point`, then this won't work. Adding `System.Drawing` will break all other Points in the project. – Casper Oct 05 '19 at 15:03
  • @Casper please, read carefully all previous comments for this answer. There is mentioned this problem multiple times. You still can use full class name with package name for source files, where you need both. – j123b567 Oct 06 '19 at 18:04
40

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.

Hele
  • 1,558
  • 4
  • 23
  • 39
Felice Pollano
  • 32,832
  • 9
  • 75
  • 115
  • 10
    Could you please edit in actual distance code too as this post is found by "distance between points"? Like `var distance = Math.Sqrt((Math.Pow(x1-x2,2)+Math.Pow(y1-y2,2)))` with comment "but usually for distance checks you'll just compare squares of distances". – Alexei Levenkov Jun 01 '16 at 23:06
  • 1
    Is there nothing built-in to C# to do this? I highly doubt we need to be defining this ourselves – Kellen Stuart Nov 29 '19 at 05:11
26

Something like this in c# would probably do the job. Just make sure you are passing consistent units (If one point is in meters, make sure the second is also in meters)

private static double GetDistance(double x1, double y1, double x2, double y2)
{
   return Math.Sqrt(Math.Pow((x2 - x1), 2) + Math.Pow((y2 - y1), 2));
}

Called like so:

double distance = GetDistance(x1, y1, x2, y2)
if(distance <= 5)
{
   //Do stuff
}
Jack Fairfield
  • 1,876
  • 22
  • 25
5

Given points (X1,Y1) and (X2,Y2) then:

dX = X1 - X2;
dY = Y1 - Y2;

if (dX*dX + dY*dY > (5*5))
{
    //your code
}
StayOnTarget
  • 11,743
  • 10
  • 52
  • 81
Roee Gavirel
  • 18,955
  • 12
  • 67
  • 94
  • 1
    Be a bit more self-documenting if you wrote 5*5 instead of 25. The compiler should optimize it out, so it has no performance consequences. – RenniePet Mar 10 '14 at 11:27
  • Note taken, thought I would guess that for this specific case it's self explanatory. – Roee Gavirel May 11 '15 at 14:21
4

Here is my 2 cents:

double dX = x1 - x2;
double dY = y1 - y2;
double multi = dX * dX + dY * dY;
double rad = Math.Round(Math.Sqrt(multi), 3, MidpointRounding.AwayFromZero);

x1, y1 is the first coordinate and x2, y2 the second. The last line is the square root with it rounded to 3 decimal places.

DarkPh03n1X
  • 600
  • 1
  • 7
  • 17
2

Based on Jack's answer, I use the following extension method:

public static class Extensions
{
    public static double DistanceTo(this Point from, Point to)
    {
        var result = Math.Sqrt(Math.Pow((from.X - to.X), 2) + Math.Pow((from.Y - to.Y), 2));
        return result;
    }
}

Which allows for the following:

var distance = point1.DistanceTo(point2);
Fidel
  • 7,027
  • 11
  • 57
  • 81
1

if u use System.Drawing.Point ;

Point p1 = new Point();
Point p2 = new Point();

Math.Pow(Math.Pow(p1.X - p2.X, 2) + Math.Pow(p1.Y - p2.Y, 2), 1 / 2);

if u use System.Windows.Point like wpf ;

Point.Subtract(_p1, _p2).Length;

eakcn94
  • 21
  • 2
1

System.Numerics has this functionality for vector 3

    /// <summary>
    /// Returns the Euclidean distance between the two given points.
    /// </summary>
    /// <param name="value1">The first point.</param>
    /// <param name="value2">The second point.</param>
    /// <returns>The distance.</returns>
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Distance(Vector3 value1, Vector3 value2) {
    if (Vector.IsHardwareAccelerated) {
        Vector3 difference = value1 - value2;
        float ls = Vector3.Dot(difference, difference);
        return (float) System.Math.Sqrt(ls);
    } else {
        float dx = value1.X - value2.X;
        float dy = value1.Y - value2.Y;
        float dz = value1.Z - value2.Z;

        float ls = dx * dx + dy * dy + dz * dz;

        return (float) System.Math.Sqrt((double) ls);
    }
}

/// <summary>
/// Returns the Euclidean distance squared between the two given points.
/// </summary>
/// <param name="value1">The first point.</param>
/// <param name="value2">The second point.</param>
/// <returns>The distance squared.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float DistanceSquared(Vector3 value1, Vector3 value2) {
    if (Vector.IsHardwareAccelerated) {
        Vector3 difference = value1 - value2;
        return Vector3.Dot(difference, difference);
    } else {
        float dx = value1.X - value2.X;
        float dy = value1.Y - value2.Y;
        float dz = value1.Z - value2.Z;

        return dx * dx + dy * dy + dz * dz;
    }
}

Reference here https://referencesource.microsoft.com/#System.Numerics/System/Numerics/Vector3.cs

0

You can use the below formula to find the distance between the 2 points:

distance*distance = ((x2 − x1)*(x2 - x1)) + ((y2 − y1)*(y2 - y1))
Gander
  • 1,854
  • 1
  • 23
  • 30
destro
  • 21
  • 2
-3

the algorithm : ((x1 - x2) ^ 2 + (y1 - y2) ^ 2) < 25