Calculating the distance between 2 points

后端 未结 7 2259
青春惊慌失措
青春惊慌失措 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: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.

提交回复
热议问题