Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
# Calculates the overlap area between two circles of radii r1 and r2 with
# center points d apart.
def circle_overlap_area(r1, r2, d):
try:
# Expression from http://mathworld.wolfram.com/Circle-CircleIntersection.html
return r2**2 * acos((d**2+r2**2-r1**2)/(2*d*r2))+r1**2*acos((d**2-r2**2+r1**2)/(2*d*r1)) - 1/2*sqrt((-d+r2+r1)*(d+r2-r1)*(d-r2+r1)*(d+r2+r1))
except:
# A few possible cases if there's a math domain error...
if r1 == r2 and d == 0:
# Identical circle radii and center points
# Intersection area rea will be the area of either circle
return pi * (r1**2)
elif d+min(r1,r2) < max(r1,r2):
# Smaller circle is completely contained within the larger circle
# Intersection area is the area of the smaller circle
return pi * (min(r1,r2)**2)
elif d > r1+r2:
# The circles don't overlap at all
# Intersection area must be 0
return 0.0
else:
# Undefined case
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment