Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a circle is contained in another circle

I'm trying to check if a circle is contained within another circle. I'm not sure if the math behind it is the problem or if its my if statement because I keep getting True for anything I pass.

#Get_center returns (x,y)
#Get_radius returns radius length
def contains(self,circle):
    distance = round(math.sqrt((circle.get_center()[0]-self.get_center()[0])**2 + (circle.get_center()[1] - self.get_center()[1])**2))
    distance_2 = distance + circle.get_radius()
    if distance_2 > distance:
        return True        #Circle 2 is contained within circle 1
like image 920
Yavaar Nosimohomed Avatar asked Nov 03 '15 02:11

Yavaar Nosimohomed


People also ask

How do you check if a circle is within another circle?

We can solve this using the Pythagorean theorem. compute the distance from the center of the circle and origin. Then if (distance – r1) >= r and (distance – r1) <= R, if both are true, then the circle is inside the ring.

How do you check if a circle is inside a polygon?

Offset the polygon inwards by distance = circle's radius. If the resulting polygon is still a valid polygon (i.e., is not self-intersecting) and maintain the same vertices traversing orientation, check if the circle's center is inside the offset polygon. If yes, the circle is inside the original polygon.

How do you know if two circles are concentric?

Concentric Circles – Theorem In two concentric circles, the chord of the larger circle, which touches the smaller circle, is bisected at the point of contact.


2 Answers

I don't know about python but the math is simple. See the below picture

enter image description here

To check if circle 2 inside circle 1,

compute d 
    d = sqrt( (x2-x1)^2 + (y2-y1)^2 );
get c2 and c1
if c1 > ( d + c2 ) 
   circle 2 inside circle 1
else
   circle 2 not inside circle 1
like image 71
CroCo Avatar answered Oct 18 '22 22:10

CroCo


CODE ACCORDING TO THE IMAGE IN THE ACCEPTED ANSWER (without getters, as it's more readable):

import math
def contains(self, circle):
  d = math.sqrt(
        (circle.center[0] - self.center[0]) ** 2 +
        (circle.center[1] - self.center[1]) ** 2)
  return self.radius  > (d + circle.radius)

I used it, and it works. In the following plot, you can see how the circles completely contained in the red big one are painted in green, and the others in black:

enter image description here

like image 32
onofricamila Avatar answered Oct 18 '22 21:10

onofricamila