Vectors
|
Introduction
This tutorial presents a relatively straight forward explanation of how the shortest
distance between a point and a line can be calculated. Readers who have searched the
internet for information on this topic know there is no shortage of confusing, and
often confused, "explanations" about point-to-line calculations.
|
To B or not to B?
The python procedure presented in listing 1 primarily depends on the use the vector dot
product to determine if the shortest
distance is Coordinate Inputs
start (1, 0, 2) end (4.5, 0, 0.5) Point:
pnt (2, 0, 0.5)
The Y coordinates of the line and point are zero and as such both lie on the XZ plane.
Step 1Convert the line and point to vectors. The coordinates of the vector representing the point are relative to the start of the line. line_vec = vector(start, end) # (3.5, 0, -1.5) pnt_vec = vector(start, pnt) # (1, 0, -1.5)
Step 2Scale both vectors by the length of the line. line_len = length(line_vec) # 3.808 line_unitvec = unit(line_vec) # (0.919, 0.0, -0.394) pnt_vec_scaled = scale(pnt_vec, 1.0/line_len) # (0.263, 0.0, -0.393)
Step 3Calculate the dot product of the scaled vectors. The value corresponds to the distance, shown in black, along the unit vector to the perpendicular, shown in green. t = dot(line_unitvec, pnt_vec_scaled) # 0.397
Step 4Clamp 't' to the range 0 to 1. Scale the line vector by 't' to find the nearest location, shown in green, to the end of the point vector. Calculate the distance from the nearest location to the end of the point vector. if t < 0.0: t = 0.0 elif t > 1.0: t = 1.0 nearest = scale(line_vec, t) # (1.388, 0.0, -0.595) dist = distance(nearest, pnt_vec) # 0.985
Step 5Translate the 'nearest' point relative to the start of the line. This ensures its coordinates "match" those of the line. nearest = add(nearest, start) # (2.388, 0.0, 1.405)
|
Listing 1 (distances.py)
Figure 9 shows 150 points in random locations and their "connections" to their nearest location on a line. |
|
© 2002- Malcolm Kesson. All rights reserved.