AB21
AB21

Reputation: 385

Finding distance of two circles in python

I am learning python programming.

enter image description here

There are two circles and they both have their own centers c1 and c2. Also any point x1,y1 lies in circle1 and x2,y2 lies in circle2. We need to create three class Circle,Line,Points. It is mandatory and we need to find distance between two circle in Circle class. Distance between two circle is given by r1+r2 of two circles. I tried to find the distance but I am getting error:

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

I am getting error ValueError: math domain error.Is there any better way to code rather than mine?

Upvotes: 0

Views: 363

Answers (2)

onno
onno

Reputation: 979

I think you should use **2 to get the square of a number. Compute r1 and r2 using:

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)

Upvotes: 0

Muhteva
Muhteva

Reputation: 2832

^ is bitwise XOR operator. Instead, you should use **2 to take the square of a number.

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

output : 5.0

Upvotes: 1

Related Questions