问题描述:
已知点P(px,py),直线L(P1,P2),求点P到L的距离。
首先,推导直线公式:
点$$P_1(x_1,y_1)$$, 点$$P_2(x_2,y_2)$$ 可知直线方程为:
$$x(y_2-y_1)-y(x_2-x_1)+y_1(x_2-x_1)-x_1(y_2-y_1)=0$$
点$$P_0(x_0,y_0)$$ 到$$P_1P_2$$的距离如下:
$$egin{array}{rcl}dist & = & frac{left|x_0(y_2-y_1)-y_0(x_2-x_1)+y_1(x_2-x_1)-x_1(y_2-y_1) ight|}{sqrt{(y_2-y_1)^2+(x_2-x_1)^2}} \& = & frac{left|(y_2-y_1)*(x_0-x_1)-(x_2-x_1)*(y_0-y_1) ight|}{sqrt{(y_2-y_1)^2+(x_2-x_1)^2}}end{array}$$
代码如下所示:
1 double getDistFromP2L(double px, double py, double p1x, double p1y, double p2x, 2 double p2y) 3 { 4 double y2_y1 = p2y - p1y; 5 double x2_x1 = p2x - p1x; 6 if (fabs(y2_y1) < EOPS && fabs(y2_y1) < EOPS) { 7 return 0.0; 8 } 9 return fabs(y2_y1 * (px - p1x) - 10 x2_x1 * (py - p1y)) / sqrt(y2_y1 * y2_y1 + x2_x1 * x2_x1); 11 }