Check if a circle is contained in another circle

有些话、适合烂在心里 提交于 2020-01-01 03:23:10

问题


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

回答1:


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

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



回答2:


You have distance_2 = distance + circle.get_radius(), so distance_2 will always be higher than distance and distance_2 > distance will always be true.




回答3:


If you want strict containment, that means that the absolute value of the difference of radii will be less than the distance between centers. You can exploit that in order to avoid taking square root (because squares of two positive numbers will have the same order as the numbers themselves):

def contains(self,circle):
    distance_squared = (circle.get_center()[0]-self.get_center()[0])**2 + (circle.get_center()[1] - self.get_center()[1])**2
    difference_squared = (self.get_radius() - circle.get_radius())**2
    return (difference_squared < distance_squared) and (self.get_radius() > circle.get_radius())

Btw, just as a style note, there is no need to write getters and setters in Python. You can just have fields and if you need to modify how they are accessed, you can override it later on (without effecting any of the classes which access them).

Making this easy from the earliest versions (maybe even from the start) was one of the reasons Python was so appealing and managed to take off. Python code tends to be very short because of this. So you don't lose sight of the forest for the trees.




回答4:


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:



来源:https://stackoverflow.com/questions/33490334/check-if-a-circle-is-contained-in-another-circle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!