计算几何求线段与交点

求线段解析式

给出直线上两点的坐标,求直线的解析式。

设两点坐标分别为 ( x 1 , y 1 ) , ( x 2 , y 2 ) (x_1,y_1),(x_2,y_2) (x1,y1),(x2,y2),解析式为 a x + b y + c = 0 ax+by+c=0 ax+by+c=0

则直线斜率为 y 2 − y 1 x 2 − x 1 \dfrac{y_2-y_1}{x_2-x_1} x2x1y2y1

− a b = y 2 − y 1 x 2 − x 1 -\dfrac{a}{b}=\dfrac{y_2-y_1}{x_2-x_1} ba=x2x1y2y1

那么 a = y 2 − y 1 , b = x 1 − x 2 a=y_2-y_1,b=x_1-x_2 a=y2y1,b=x1x2

( x 1 , y 1 ) (x_1,y_1) (x1,y1)代入 a x + b y + c = 0 ax+by+c=0 ax+by+c=0,得 c = x 2 y 1 − x 1 y 2 c=x_2y_1-x_1y_2 c=x2y1x1y2

{ a = y 2 − y 1 b = x 1 − x 2 c = x 2 y 1 − x 1 y 2 \left\{\begin{matrix}a=y_2-y_1\\b=x_1-x_2\\ c=x_2y_1-x_1y_2\end{matrix}\right. a=y2y1b=x1x2c=x2y1x1y2

code

struct point{
	double x,y;
};
double a,b,c;
void gt(point v1,point v2){
	a=v2.y-v1.y;
	b=v1.x-v2.x;
	c=v2.x*v1.y-v1.x*v2.y;
}

求交点

给出两条直线的解析式,求交点。

设两条直线的解析式为 { a 1 x + b 1 y + c 1 = 0 a 2 x + b 2 y + c 2 = 0 \left\{\begin{matrix}a_1x+b_1y+c_1=0\\a_2x+b_2y+c_2=0 \end{matrix}\right. {a1x+b1y+c1=0a2x+b2y+c2=0

一式两边同时乘 a 2 a_2 a2,二式两边同时乘 a 1 a_1 a1

{ a 1 a 2 x + a 2 b 1 y + a 2 c 1 = 0 a 1 a 2 x + a 1 b 2 y + a 1 c 2 = 0 \left\{\begin{matrix}a_1a_2x+a_2b_1y+a_2c_1=0\\a_1a_2x+a_1b_2y+a_1c_2=0 \end{matrix}\right. {a1a2x+a2b1y+a2c1=0a1a2x+a1b2y+a1c2=0

一式减二式得 ( a 2 b 1 − a 1 b 2 ) y + a 2 c 1 − a 1 c 2 = 0 (a_2b_1-a_1b_2)y+a_2c_1-a_1c_2=0 (a2b1a1b2)y+a2c1a1c2=0

解得 y = a 1 c 2 − a 2 c 1 a 2 b 1 − a 1 b 2 y=\dfrac{a_1c_2-a_2c_1}{a_2b_1-a_1b_2} y=a2b1a1b2a1c2a2c1

同理 x = b 1 c 2 − b 2 c 1 a 1 b 2 − a 2 b 1 x=\dfrac{b_1c_2-b_2c_1}{a_1b_2-a_2b_1} x=a1b2a2b1b1c2b2c1


{ x = b 1 c 2 − b 2 c 1 a 1 b 2 − a 2 b 1 y = a 1 c 2 − a 2 c 1 a 2 b 1 − a 1 b 2 \left\{\begin{matrix}x=\dfrac{b_1c_2-b_2c_1}{a_1b_2-a_2b_1}\\\\y=\dfrac{a_1c_2-a_2c_1}{a_2b_1-a_1b_2}\end{matrix}\right. x=a1b2a2b1b1c2b2c1y=a2b1a1b2a1c2a2c1


当然,要先判断两条直线是否平行。

若平行,则 − a 1 b 1 = − a 2 b 2 -\dfrac{a_1}{b_1}=-\dfrac{a_2}{b_2} b1a1=b2a2,此时 a 1 b 2 − a 2 b 1 = 0 a_1b_2-a_2b_1=0 a1b2a2b1=0,上式分母为 0 0 0

code

struct line{
	double a,b,c;
};
const double eps=1e-8;
double vx,vy;
bool find(point v1,point v2){
	if(fabs(v1.a*v2.b-v1.b*v2.a)<eps) return 0;
	vx=(v1.b*v2.c-v2.b*v1.c)/(v1.a*v2.b-v2.a*v1.b);
	vy=(v1.a*v2.c-v2.a*v1.c)/(v2.a*v1.b-v1.a*v2.b);
	return 1;
}

你可能感兴趣的:(数学,数学,c++)