计算几何-园的问题
一.圆与圆的位置关系
1.两圆交的面积 两圆如果相交,则交的面积是一个弓形。考虑到两个圆相交的面积只与圆心距相关。我们可以对圆进行平移旋转,使得两个圆的圆心分别为(0,0)和(d,0).
模板如下:
double CircleCrossArea(Circle A,Circle B){ double r1 = A.r, r2 = B.r; double d = Dis(A.o, B.o),r=min(r1,r2); if (RlCmp(d, r1 + r2) >= 0) return 0; //相离或者外切 if (RlCmp(d, abs(r1 - r2)) <= 0) return pi*r*r; //内含 //将r1放在圆心 double x1 = (d*d + r1*r1 - r2*r2) / (2 * d); double s1 = x1*sqrt(r1*r1 - x1*x1) - r1*r1*acos(x1/r1); //将r2放在圆心 double x2 = (d*d + r2*r2 - r1*r1) / (2 * d); double s2 = x2*sqrt(r2*r2 - x2*x2) - r2*r2*acos(x2 / r2); return abs(s1 + s2); }
2.两圆交点 两圆位置关系一共有5中。我们将其归纳为3种,0个交点,个交点,1个交点,2个交点.并且将重合也看为0个交点,模板如下:
int CirCleCrossCircle(Circle A,Circle B,Point&p1,Point&p2){ double d = Dis(A.o, B.o); //圆心距 double r1 = A.r, r2 = B.r; if (RlCmp(d, r1 + r2) > 0||RlCmp(d,abs(r1-r2))<0) return 0; //内含或者相离 if (A.o == B.o&&RlCmp(r1, r2) == 0) return 0; //重合 double cos_angle = (r1*r1 + d*d - r2*r2) / (2 * r1*d); //余弦定理 double sin_angle = sqrt(1 - cos_angle*cos_angle); //求sin Point q = (r1*cos_angle/d)*(B.o - A.o) + A.o; //交点连线与圆心连线的交点 Point pt = (1.0/d)*Point(A.o.y - B.o.y, B.o.x - A.o.x); //交点方向的单位向量 p1 = q + (r1*sin_angle)*pt; p2 = q - (r1*sin_angle)*pt; if (p1 == p2) return 1; return 2; }
3.直线与圆相交问题 直线与圆相交,只需将直线到圆心距离与圆半径比较就可以。
//圆C与直线AB相交 int CircleCrossLine(Point A,Point B,Circle C,Point&p1,Point&p2){ double d = PointToLine(C.o, A, B); double r = C.r; if (RlCmp(r, d)<0) return 0; //直线与圆相离 Point q = PointProjLine(C.o, A, B); double l = sqrt(r*r - d*d); Point s = (1.0/Dis(A, B))*(B - A); //AB单位方向向量 p1 = q + l*s; p2 = q - l*s; if (RlCmp(d, r) == 0) return 1; return 2; }