1
$\begingroup$

I want to determine the distance between a point and a line (represented by two points).

I found the following calculation on Wikipedia, and cannot determine how it works. It's seems simple, but for some reason the explanation eludes me.

The following Java snippet provide distance from point P to the line that passes through A-B:

public double pointToLineDistance(Point A, Point B, Point P) {  double length = Math.hypot(B.x - A.x, B.y - A.y);  return Math.abs((P.x - A.x) * (B.y - A.y) - (P.y - A.y) * (B.x - A.x)) / length; } 

Normal length is calculating the the distance from point A to B (the red line) by determining the x and y differences in the two points and using the Pythagorean theorem.

Example graph

(P.x - A.x) - green line

(B.y - A.y) - b

(P.y - A.y) - blue line

(B.x - A.x) - a

I'm not sure why we multiply the respective distances, perform subtraction, and then divide by the length of the red line.

Presumably it has to do with: $\frac{|a\cdot x+b\cdot y+c|}{\sqrt{a^2+b^2}}$

but I'm just not connecting the two.

UPDATE(9/18/12)

According to bubba, the code isn't implementing the equation above. Bubba gave a good explanation, but I had two questions and a request in response to his answer:

  • How/why do we know that d is equal to that?
  • Why do we then divide the cross product by the length?
  • Would you mind running through the example?

2 Answers 2

3

The code isn't really using the formula you gave.

Instead, the reasoning in the code is as follows:

Let $\theta$ be the angle between the vector $P-A$ and the vector $B-A$. Then $d = \|(P-A)\| \sin\theta$.

But, also, we have, from the definition of the cross product: $\|(P-A)\times(B-A)\|=\|(P-A)\|\cdot\|(B-A)\|\sin\theta$ A little bit of algebra then gives us: $d = \frac{\|(P-A)\times(B-A)\|}{\|(B-A)\|}$ That's the formula used in the code.

The first line calculates $length = \|(B-A)\|$, and then the second line calculates the cross product divided by this $length$.

  • 0
    It will be obvious if you draw a picture. It just comes from the relationship sine = opposite/hypotenuse.2012-09-21
1

The link:Wiki-Distance from line to a point, should answer the first 2 bullets - See the section "Algebraic Proof".

As for an example you have asked for, I will use the points you gave.

point $(m,n)=(3,4)$

Line's equation is:

$ax + by + c$

from the points $(3,5)$ and $(1,2)$, you can find the line equation to be:

$-3x + 2y - 1 = 0$

as a result

$a=-3, b=2, c=-1, m=4, n=3$

since

$d=\frac{ABS(a*m+b*n+c)}{(\sqrt{((a*a+b*b)})}$

so

$d=\frac{ABS(-3*4+2*3+(-1))}{(\sqrt{((-3)*(-3)+(2)*(2))})}$

$d=1.94145068679$

enter image description here

  • 0
    I suggest you start a new question and tag it with "vectors" to focus on a vector solution. I am not good enough with vectors.2012-09-19