Check if a circle is contained in another circle

前端 未结 4 762
青春惊慌失措
青春惊慌失措 2020-12-15 12:33

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

4条回答
  •  生来不讨喜
    2020-12-15 13:27

    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.

提交回复
热议问题