194 Chapter 6 Distance in 2D
6.2 Point to Polyline
For calculating the distance between a point Y and a polyline L with vertices P
0
through P
n
and line segments S
i
,0≤i<n, whose end points are P
i
and P
i+1
, the
straightforward algorithm is to calculate the minimum of the distances between the
point and the line segments of the polyline:
Distance
2
(Y , L) = min
0≤i<n
Distance
2
(Y , S
i
) (6.7)
Iterating blindly over the line segments can potentially be expensive for polylines with
a large number of segments or for an application with a large number of polylines for
which the distance calculations must be made frequently.
A variation is to use rejection methods that determine that a line segment is not
sufficiently close enough to the test point that it could replace the currently known
minimum distance, µ. The savings in time occurs by avoiding the potential division
that occurs when the closest point to Y on a line segment is interior to that segment.
Let Y = (a, b).Aslongasµ remains the current minimum, any line segment that
is outside the circle with center Y and radius µ is farther away from Y than µ,so
that segment cannot cause an update of µ. Figure 6.4 illustrates this. The segments
S
1
and S
2
are rejected for the full calculation of distance because both are outside the
circleofradiusµ centered at Y . The segment S
3
is not rejected since it intersects
the circle. However, this begs the question since the rejection tests require comput-
ing the distances from the segments to Y , exactly the tests we are trying to avoid!
A faster, but coarser, rejection test uses axis-aligned infinite strips that contain the
circle. Let S
i
=(x
i
, y
i
), (x
i+1
, y
i+1
)be the next segment to be tested. If S
i
is outside
the infinite strip |x − a|≤µ, then it cannot intersect the circle. The rejection test is
therefore
|x
i
− a|≤µ and |x
i+1
− a|≤µ and (x
i
− a)(x
i+1
− a) > 0
The first two conditions guarantee each segment end point is outside the strip. The
last condition guarantees that the end points are on the same side of the strip. Simi-
larly, if S
i
is outside the infinite strip |y − b|≤µ, then it cannot intersect the circle.
The rejection test is
|y
i
− b|≤µ and |y
i+1
− b|≤µ and (y
i
− b)(y
i+1
− b) > 0
Figure 6.4 illustrates this. The segment S
1
, although outside the circle, is not rejected
because it partly lies in each infinite strip. However, S
2
is rejected because it is outside
the vertical strip.
Since square roots should be avoided in the intermediate calculations, an imple-
mentation maintains the squared-distance µ
2
instead of µ. The rejection test must
be restructured accordingly to use µ
2
: