Finding center of a circle given two points and radius

You can't necessarily always find a unique center point give two points and a radius. In fact there are three distinct cases:

        

Case 1:

                                  

happens when the given diameter is smaller than the distance between the given points. In this case there are no solutions.

Case 2:

                                  

happens when the given diameter is exactly equal ot the distance between two points. In this case there is a trivial solution of

                                  

Case 3:

happens when the given diameter is more than the distance between the two points. In this case there are two solutions from the equations:

                                  

which you can find solutions for example from this page:

                               

where q is the distance between the two points and [x3, y3] is the middle point.

   


Here in this Gist I'm trying to implement these in C, however not finished yet. feel free to continue from where I have left.


Given the equation of a circle and the equations of the midpoints:

q = sqrt((x2-x1)^2 + (y2-y1)^2)

y3 = (y1+y2)/2

x3 = (x1+x2)/2

One answer will be:

x = x3 + sqrt(r^2-(q/2)^2)*(y1-y2)/q 

y = y3 + sqrt(r^2-(q/2)^2)*(x2-x1)/q  

The other will be:

x = x3 - sqrt(r^2-(q/2)^2)*(y1-y2)/q

y = y3 - sqrt(r^2-(q/2)^2)*(x2-x1)/q  

Assuming the variables for the points have been declared already, your code should look like this:

double q = Math.Sqrt(Math.Pow((x2-x1),2) + Math.Pow((y2-y1),2));

double y3 = (y1+y2)/2;

double x3 = (x1+x2)/2;

double basex = Math.Sqrt(Math.Pow(r,2)-Math.Pow((q/2),2))*(y1-y2)/q; //calculate once
double basey = Math.Sqrt(Math.Pow(r,2)-Math.Pow((q/2),2))*(x2-x1)/q; //calculate once

double centerx1 = x3 + basex; //center x of circle 1
double centery1 = y3 + basey; //center y of circle 1
double centerx2 = x3 - basex; //center x of circle 2
double centery2 = y3 - basey; //center y of circle 2

source: http://mathforum.org/library/drmath/view/53027.html


This will return one center point. You will need to alter it for the other.

In c#:

 private double CenterX(double x1,double y1, double x2, double y2,double radius)
    {
        double radsq = radius * radius;
        double q = Math.Sqrt(((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1)));
        double x3 = (x1 + x2) / 2;


     return x3 + Math.Sqrt(radsq - ((q / 2) * (q / 2))) * ((y1 - y2) / q);


    }

    private double CenterY(double x1, double y1, double x2, double y2, double radius)
    {
    double radsq = radius * radius;
    double q = Math.Sqrt(((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1)));

     double y3 = (y1 + y2) / 2;

      return y3 + Math.Sqrt(radsq - ((q / 2) * (q / 2))) * ((x2-x1) / q);


    }