使用for循环的最小距离

时间:2014-03-13 00:27:22

标签: python distance

对于多个点,我正在计算距(x, y)中的参考点的距离。我怎样才能找到距离的最小值?这些是我写的代码行:

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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]

不是从文件中读取点并单独保存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)

您现在可以使用点成员方法测试所有点的差异。

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