I have three points on the circumference of a circle:
pt A = (A.x, A.y); pt B = (B.x, B.y); pt C = (C.x, C.y);
How do I calculate the center of the circle?
Implementing it in Processing (Java).
I found the answer and implemented a working solution:
pt circleCenter(pt A, pt B, pt C) {
float yDelta_a = B.y - A.y;
float xDelta_a = B.x - A.x;
float yDelta_b = C.y - B.y;
float xDelta_b = C.x - B.x;
pt center = P(0,0);
float aSlope = yDelta_a/xDelta_a;
float bSlope = yDelta_b/xDelta_b;
center.x = (aSlope*bSlope*(A.y - C.y) + bSlope*(A.x + B.x)
- aSlope*(B.x+C.x) )/(2* (bSlope-aSlope) );
center.y = -1*(center.x - (A.x+B.x)/2)/aSlope + (A.y+B.y)/2;
return center;
}
I was looking for a similar algorithm when I hovered over this question. Took your code but found that this will not work in cases when where either of the slope is 0 or infinity (can be true when xDelta_a or xDelta_b is 0).
I corrected the algorithm and here is my code. Note: I used objective-c programming language and am just changing the code for point value initialization, so if that is wrong, I am sure programmer working in java can correct it. The logic, however, is the same for all (God bless algorithms!! :))
Works perfectly fine as far as my own functional testing is concerned. Please let me know if logic is wrong at any point.
It can be a rather in depth calculation. There is a simple step-by-step here: http://paulbourke.net/geometry/circlesphere/. Once you have the equation of the circle, you can simply put it in a form involving H and K. The point (h,k) will be the center.
(scroll down a little ways at the link to get to the equations)
Here's my Java port, dodging the error condition when the determinant disappears with a very elegant
IllegalArgumentException
, my approach to coping with the "points are two far apart" or "points lie on a line" conditions. Also, this computes the radius (and copes with exceptional conditions) which your intersecting-slopes approach will not do.See algorithm from here: