Skip to content

Instantly share code, notes, and snippets.

@amakukha
Last active August 18, 2018 08:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amakukha/5019bfd4694304d85c617df0ca123854 to your computer and use it in GitHub Desktop.
Save amakukha/5019bfd4694304d85c617df0ca123854 to your computer and use it in GitHub Desktop.
Percentage area overlap between circles in Python.
#!/usr/bin/python
## Percentage area overlap between circles in Python.
## Inspired by PHP code by JP Hastings-Spital:
## https://gist.github.com/jphastings/316058
import math
def circle_overlap(centers_distance, radius1, radius2):
# Make sure the larger circle is left-most (for convenience)
R, r = max(radius1, radius2), min(radius1, radius2)
# Special cases: no overlap and full overlap
if centers_distance >= R + r:
return 0.0 # 0% overlap
elif R >= centers_distance + r:
return 1.0 # 100% overlap
# Else: partial overlap
R2, r2 = R**2, r**2
# Distance of cross-point from origin of larger circle
x1 = (centers_distance**2 - R2 + r2 )/(2*centers_distance)
# Distance of cross-point from origin of smaller circle
x2 = abs(centers_distance - x1)
y = math.sqrt(R2 - x1**2)
# Area of smaller lens
a1 = R2 * math.atan2(y, x1) - x1*y
# Area of larger lens
if x1 <= centers_distance:
a2 = r2 * math.atan2(y, x2) - x2*y
else:
# Special case: if the cross-point is further away from the origin of
# the first circle than the second circle is, then a2 needs to be the
# large side of the circle, not the small one:
a2 = math.pi * r2 - a2
overlap_area = a1 + a2
# Return the ratio between overlap area and smaller circle area
return overlap_area / (math.pi * r2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment