计算两点之间的距离 [英] Calculating the distance between 2 points
问题描述
我有两个点(x1,y1)和(x2,y2).我想知道这些点之间是否在5米之内.
I have two points (x1,y1) and (x2,y2). I want to know whether the points are within 5 meters of one another.
推荐答案
测量从一个点到另一个点的平方距离:
measure the square distance from one point to the other:
((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)) < d*d
其中d是距离,(x1,y1)是基点"的坐标,(x2,y2)是要检查的点的坐标.
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.
或者,如果您愿意:
(Math.Pow(x1-x2,2)+Math.Pow(y1-y2,2)) < (d*d);
注意到优选的一个出于速度原因根本不调用Pow,而第二个(可能较慢)也不出于性能原因也不调用 Math.Sqrt
.在您的情况下,这种优化也许还为时过早,但是对于必须多次执行该代码的情况,它们很有用.
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.
这篇关于计算两点之间的距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!