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.
(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?