Calculating the distance between 2 points

后端 未结 7 2260
青春惊慌失措
青春惊慌失措 2020-12-17 18:37

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

相关标签:
7条回答
  • 2020-12-17 19:18

    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.

    0 讨论(0)
  • 2020-12-17 19:20

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

    dX = X1 - X2;
    dY = Y1 - Y2;
    
    if (dX*dX + dY*dY > (5*5))
    {
        //your code
    }
    
    0 讨论(0)
  • 2020-12-17 19:25

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

    0 讨论(0)
  • 2020-12-17 19:28

    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
    }
    
    0 讨论(0)
  • 2020-12-17 19:32

    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;
    
    0 讨论(0)
  • 2020-12-17 19:35

    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.

    0 讨论(0)
提交回复
热议问题