Reputation: 21
When searching for code to calculate the circle out of 3 points it leads me to this code:
def circleRadius(b, c, d):
temp = c[0]**2 + c[1]**2
bc = (b[0]**2 + b[1]**2 - temp) / 2
cd = (temp - d[0]**2 - d[1]**2) / 2
det = (b[0] - c[0]) * (c[1] - d[1]) - (c[0] - d[0]) * (b[1] - c[1])
if abs(det) < 1.0e-10:
return None
# Center of circle
cx = (bc*(c[1] - d[1]) - cd*(b[1] - c[1])) / det
cy = ((b[0] - c[0]) * cd - (c[0] - d[0]) * bc) / det
radius = ((cx - b[0])**2 + (cy - b[1])**2)**.5
return radius
Based on Stackoverflow and Dr.Math. The code works perfectly, but I don't understand how the code fits to the explanation given at Dr.Math.
Can anyone help me to understand why the code is working and what substeps are implemented in the variables?
Upvotes: 1
Views: 6190
Reputation:
Not really an answer, I am showing here an alternative method.
Let p
, q
, r
be the three points. We translate them so that p
comes to the origin. Vectorially, q-= p
, r-= p
.
Now the equation of a point by the origin is
2.xc.x + 2.yc.y = x² + y²
where xc
, yc
are the coordinates of the center.
The plugging the coordinates of p
, q
, we get a 2x2 system
xc.xp + yc.yp = xp² + yp²
xc.xq + yc.yq = xq² + yq²
The code that implements this is given below
# Translate to the origin
xq-= xp
yq-= yp
q2= xp * xp + yp * yp
xr-= xq
yr-= yq
r2= xr * xr + yr * yr
# Solve for the center coordinates
d= 2 * (xp * yq - xq * yp)
xc= (p2 * yq - q2 * yp) / d
yc= (p2 * xp - q2 * xq) / d
# Radius
r= math.sqrt(xc * xc + yc * yc)
# Untranslate
xc+= xp
yc+= yp
Upvotes: 0
Reputation: 1157
The code you see is a "simplified" and concise formula of the procedure described in the Dr. Math page.
Let us go over it step-by-step.
For the sake of simplicity and adhering to mathematical notations, let be the points on the triangle. [b is point 1, c is point 2, and d is point 3]
For such triangle, the area is defined as:
This variable det
in the function is equal to 2 * area of the triangle.
The if abs(det) < 1.0e-10:
is checking for collinearity. If the area is close to zero, the points given are collinear i.e. they are points on a single line.
Find the slopes of the lines L1, L2 passing through points b, c & c, d
Find the equations for lines L3, L4, which are the perpendicular bisectors of line sL1 and L2 respectively.
Find the intersection of lines L3 and L4, which is nothing but the center of the cirle.
Do all the substitutions and you can see it all come together.
Upvotes: 1