Center and Radius of a circle given 3 points

#include<bits/stdc++.h>
#define ll long long

// input: 3 points in circle. 
// output: center and radius of circle.
// require: 3 points not in a line.
pair<pair<double, double>, double> get_center_and_radius(double x1, double y1, double x2, double y2, double x3, double y3) {
    
    // make sure (y1 != y2 && y1 != y3)
    if (!(y1 != y2 && y1 != y3)) {
        double t1, t2;
        t1 = x1, t2 = y1;
        x1 = x2, y1 = y2;
        x2 = t1, y2 = t2;
        
        if (!(y1 != y2 && y1 != y3)) {
            double t1, t2;
            t1 = x1, t2 = y1;
            x1 = x3, y1 = y3;
            x3 = t1, y3 = t2;
        }
    }
    
    double u = 2.*x1 - 2.*x2;
    double v = x2*x2 + y2*y2 - x1*x1 - y1*y1;
    double w = 2.*y2 - 2.*y1;

    double e = 2.*x1 - 2.*x3;
    double f = x3*x3 + y3*y3 - x1*x1 - y1*y1;
    double g = 2.*y3 - 2.*y1;
    
    double a = (f*w - v*g) / (u*g - e*w);
    double b = (x2*x2 + y2*y2 + 2.*a*x1 - x1*x1 - y1*y1 - 2.*a*x2) / (2.*y2 - 2.*y1);
    double c = - (x1*x1 + y1*y1 - 2.*a*x1 - 2.*b*y1);
    double r = sqrt(a*a + b*b -c);
    
    pair<pair<double, double>, double> result = make_pair(make_pair(a, b), r);
    return result;
    
}
    

Leave a Reply