2014-03-13 83 views
0

對於許多點,我正在計算位於(x, y)中的參考點的距離。我怎樣才能找到距離的最小值?這些是我寫的代碼行:使用for循環的最小距離

for k in range(0, 10): 
    dist = math.sqrt((x - data.X[k])**2 + (y - data.Y[k])**2) 
+0

你如何存儲你正在比較的點? – inspectorG4dget

+0

這些點具有座標'(X [k],Y [k])'。我從文件中讀取它們,然後在寫入輸出文件之前將它們存儲起來。 –

回答

1

你的意思是這樣的嗎?

min=math.sqrt((x - data.X[0])**2 + (y - data.Y[0])**2) 
for k in range(0, 10): 
    dist = math.sqrt((x - data.X[k])**2 + (y - data.Y[k])**2) 
    if dist<min: 
     min=dist 

或者:

for k in range(0, 10): 
    dist = math.sqrt((x - data.X[k])**2 + (y - data.Y[k])**2) 
    try: 
     if dist<min: 
      min=dist 
    except NameError: 
     min=dist 
+0

正是......感謝您展示如何使用'try'! –

+0

如何獲得最小值對應的'k'值? –

+0

@albus_c'data.index(min)'應該做的伎倆。引用[this](http://docs.python.org/2/tutorial/datastructures.html#more-on-lists):_list.index(x):返回第一個項目列表中的索引,其值爲X。這是一個錯誤,如果沒有這樣的item._另外,關於使用'try',請參見[here](http://docs.python.org/2/glossary.html#term-eafp) – Dunno

1

類是你的朋友。這有點多,但它更好,而且是可擴展的。

class point: 
    def __init__(self, x, y): 
     self.x = x 
     self.y = y 

    def __str__(self): 
     return '{0}, {1}'.format(self.x, self.y) 

    def distanceto(self, other): 
     return math.sqrt((self.x - other.x)**2 + (self.y - other.y)**2) 

    def closestpoint(self, pointlist): 
     pointinfo = [{'point':x, 'dist':self.distanceto(x)} for x in pointlist] 
     pointinfo.sort(key=lambda p: p.dist) 
     return pointinfo[0] 

而不是從文件中讀取點和seperately保存XY組件,爲什麼不將它們保存爲點的列表?

# all points read from the file. 
listofpoints = [] 
for i in range(0, 10): 
    listofpoints.append(point(data.X[i], data.Y[i])) 

# the point you'd like to test against. 
mytestpoint = point(0,0) 

您現在可以使用point成員方法測試所有點的差異。

closest = mytestpoint.closestpoint(listofpoints) 
print 'Closest point is at {0} and is a distance of {1} from {2}'.format(
    closest, 
    mytestpoint.distanceto(closest), 
    mytestpoint)