python - 在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
消息。有没有比我的更好的编码方式?
解决方案
^
是按位异或运算符。相反,您应该使用**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
推荐阅读
- ruby-on-rails - 如何在 Ruby 中将独占范围转换为包含范围?
- autohotkey - SHIFT 的 AutoHotKey 修饰符符号“+”不起作用
- javascript - 我可以让 JSON.stringify 包含值未定义的键吗?
- php - 如何一次在不同的 2 div 中获取数据?
- c++ - QSvgGenerator 在生成 Svg 时将 QSvgGraphicsItem 转换为图像
- blender - 让一个对象模仿另一个动画对象的旋转
- php - 通过键查询对象
- javascript - JS ES6 通过键数组过滤对象的正确方法
- python - Python - 从分叉的 GitHub 存储库安装
- javascript - 根据从 - 到的选择计算价格