Circles - Cross Points of Circles


デカルト座標で解いたが傾きが0の場合と無限の場合で場合わけもっときれいに解けないかな。
2円の交点に関する問題は冪とかいろいろと奥深い内容があったような?

#include<stdio.h>
#include<algorithm>
#include<math.h>
struct E{
   double x,y;
   bool operator<(const E& e1)const{
       if(x!=e1.x)return x<e1.x;
       return y<e1.y;
   }
};


void f( double cx,double cy,double r,
   double x1,double y1,double x2,double y2){
    
   x1-=cx;
   y1-=cy;
   x2-=cx;
   y2-=cy;
   double x4,y4;
   x4=x2-x1;
   y4=y2-y1;
   double a,b,c,d,t1,t2;
   a=x4*x4+y4*y4;
   b=2*x1*x4+2*y1*y4;
   c=x1*x1+y1*y1-r*r;
   d=b*b-4*a*c;
   if(d<0)d=0;
   t1=(-b-sqrt(d))/(2.0*a);
   t2=(-b+sqrt(d))/(2.0*a);
   E ans[2];
   ans[0].x=x1+t1*x4+cx;
   ans[0].y=y1+t1*y4+cy;
   ans[1].x=x1+t2*x4+cx;
   ans[1].y=y1+t2*y4+cy;
   std::sort(ans,ans+2);
   printf("%.8lf %.8lf %.8lf %.8lf\n",ans[0].x,ans[0].y,ans[1].x,ans[1].y);
}

int main(){
   double cx1,cy1,r1,cx2,cy2,r2,r3;
   int q;
   scanf("%lf %lf %lf %lf %lf %lf",&cx1,&cy1,&r1,&cx2,&cy2,&r2);
   r3=r2*r2-r1*r1;
   cx2-=cx1;
   cy2-=cy1;
   double a,b,c,x1,x2,y1,y2;
   a=-2*cx2;
   b=-2*cy2;
   c=cx2*cx2+cy2*cy2-r3;
   if(a==0){
       y1=-c/b;
       x1=0;
        
       y2=y1;
       x2=1;
   }else if(b==0){
       x1=-c/a;
       y1=0;
        
       x2=x1;
       y2=1;
   }else{
       x1=0;
       y1=-c/b;

       x2=-c/a;
       y2=0;
   }
   x1+=cx1;
   x2+=cx1;
   y1+=cy1;
   y2+=cy1;
   f(cx1,cy1,r1,x1,y1,x2,y2);
}
最終更新:2016年11月08日 09:46