首页 > 解决方案 > 在python中查找两个圆的距离

问题描述

我正在学习python编程。

在此处输入图像描述

有两个圆,它们都有自己的中心 c1 和 c2。此外,任何点 x1,y1 位于 circle1 中,x2,y2 位于 circle2 中。我们需要创建三个类Circle,Line,Points。这是强制性的,我们需要在Circle 类中找到两个圆之间的距离。两个圆之间的距离由两个圆给出r1+r2。我试图找到距离,但出现错误:

import math 
class Point:
    def __init__(self,x,y):
        self.x=x
        self.y=y
     
class Line:
       
    def __init__(self,p1,p2):
        self.p1=p1
        self.p2=p2

class circle:
    
    def __init__(self,l1,l2):
        self.l1=l1
        self.l2=l2
        
    def calculatedistance(self):
        r1=math.sqrt((self.l1.p1.x-self.l1.p2.x)^2+(self.l1.p2.x-self.l1.p2.x)^2)
        r2=math.sqrt((self.l2.p1.y-self.l2.p2.y)^2+(self.l2.p2.y-self.l2.p2.y)^2)
        total_distance=r1+r2
        return total_distance 

center1=Point(1,2)
point1=Point(3,4)
center2=Point(2,3)
point2=Point(5,6)

line1=Line(center1,point1)
line2=Line(center2,point2)

circle1=circle(line1,line2)
circle1.calculatedistance()

我收到错误ValueError: math domain error消息。有没有比我的更好的编码方式?

标签: python

解决方案


^是按位异或运算符。相反,您应该使用**2取数字的平方。

import math 
class Point:
    def __init__(self,x,y):
        self.x=x
        self.y=y
     
class Line:
       
    def __init__(self,p1,p2):
        self.p1=p1
        self.p2=p2

class circle:
    
    def __init__(self,l1,l2):
        self.l1=l1
        self.l2=l2
        
    def calculatedistance(self):
        r1=math.sqrt((self.l1.p1.x-self.l1.p2.x)**2+(self.l1.p2.x-self.l1.p2.x)**2)
        r2=math.sqrt((self.l2.p1.y-self.l2.p2.y)**2+(self.l2.p2.y-self.l2.p2.y)**2)
        total_distance=r1+r2
        return total_distance 

center1=Point(1,2)
point1=Point(3,4)
center2=Point(2,3)
point2=Point(5,6)

line1=Line(center1,point1)
line2=Line(center2,point2)

circle1=circle(line1,line2)
circle1.calculatedistance()

输出:5.0


推荐阅读