2015-11-03 565 views
0

我正在尝试检查圆圈是否包含在另一个圆圈内。我不确定它背后的数学问题是否是问题,或者它是否属于我的陈述,因为我通过任何事情都会收到True检查另一个圆圈是否包含圆圈

#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 
+0

你的意思是彻底包含吗?还是部分? – CroCo

+0

@CroCo整个圆圈必须被包含 –

+0

你不觉得自我半径应该进入计算吗? – agentp

回答

9

我不知道python,但数学很简单。见下面的图片

enter image description here

要检查是否圈2的内侧圈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 
+0

不错的图片,让回答显而易见。 –

+0

图片真的很明显,非常感谢! –

2

你有distance_2 = distance + circle.get_radius(),所以distance_2总是会高于distancedistance_2 > distance永远是正确的。

1

如果你想严格的遏制,这意味着半径之差的绝对值将小于中心之间的距离。你可以利用这一点,以避免采取平方根(因为两个正数的平方将有相同的顺序号本身):

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()) 

顺便说一句,只是作为一个样式注意,没有必要写getter和setter在Python中。你可以只有字段,如果你需要修改它们的访问方式,你可以稍后重写它(不影响任何访问它们的类)。

从最早的版本(甚至可能从一开始)就可以轻松实现这一点,这也是Python如此吸引人并且设法起飞的原因之一。由于这个原因,Python代码往往非常短。所以你不会忽略树木的森林。