11. Point-line distance

There are several ways that you can attack this problem. I'm going to use a parameterized approach similar to the one used for Problem 29. Line-line intersection.

Suppose the point is (px, py) and the line is given by p0 + t × v. Then the distance between the point and a point on the line is given by the following:

We need to find the value of t that minimizes this equation. You can do that with one trick and a little calculus.

The trick is to note that the minimum of this equation has the same X coordinate that minimizes the equation squared. The following shows the squared equation:

Here comes the calculus. To minimize this equation, we take the derivative of the equation with respect to it, set it equal to zero, and solve for t. The following code shows the new equation:

We can divide both sides by 2 and rearrange a bit to get the following:

Now we can solve for t:

The denominator is zero (and hence the fraction cannot be calculated) only if the vector v has zero length. In that case, the line isn't really a line, so the calculation doesn't make sense.

After you use this equation to solve for t, you can use it to find the point on the line that is closest to the target point p.

Download the PointLineDistance example solution to see additional details.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.172.195