[英]Distance between two points using the distance formula
所以我需要計算當前點和參數中指定的另一個點之間的距離並返回計算出的距離
我的打印語句需要看起來像這樣:
> print p1.distance(p2)
5.0
我當前的代碼:
import math
class Geometry (object):
next_id = 0
def __init__(self):
self.id = Geometry.next_id
Geometry.next_id += 1
geo1 = Geometry()
print geo1.id
geo2 = Geometry()
print geo2.id
class Point(Geometry):
next_id = 0
def __init__(self,x,y,):
self.x = x
self.y = y
self.id = Point.next_id
Point.next_id += 1
def __str__(self):
return "(%0.2f, %0.2f)" % (self.x, self.y)
def identify():
if(p0.id == p1.id):
print "True"
else:
print "False"
def equality():
if (self.x == self.y):
print "True"
else:
print "False"
def distance(p0, p1):
p1 = pts1
pts1 = [(7.35,8.20)]
p0 = pts0
pts0 = [(5,5)]
dist = math.sqrt((p0[0] - p1[0])**2 + (p0[1] - p1[1])**2)
return dist
p0 = Point(5,5)
print p0.id
p1 = Point(7.35,8.20)
print p1.id
print p1
print p0 == p1
print p0.id == p1.id
我不確定如何在Point類中分離x和y值,以用於方程式。
def distance(self, other):
return math.sqrt((self.x - other.x)**2 + (self.y - other.y)**2)
您從未為some_point[index]
定義行為,所以它失敗了。 以保存變量的方式訪問變量。
您應該使用p0.x
, p0.y
, p1.x
, p1.y
。 但是您不應該覆蓋參數變量。
def distance(p0, p1):
dist = math.sqrt((p0.x - p1.x)**2 + (p0.y - p1.y)**2)
return dist
你distance
的方法應該對自己點上運行( self
,因為你在做__str__
),另一點(還不如叫它p
,或可能像other
)。
def distance(self, other):
dist = math.sqrt((other.x - self.x) ** 2 + (other.y - self.y) ** 2)
return dist
使用示例:
p0 = Point(2, 4)
p1 = Point(6, 1)
print(str(p0.distance(p1)))
# 5.0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.