Question

For a number of points, I am calculating the distance from a reference point located in (x, y). How can I find the minimum of the distance? These are the code lines I wrote:

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

Solution

You mean something like this?

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

Alternatively:

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

OTHER TIPS

Classes are your friend. This is a bit more work, but it's nicer, and it's extensible.

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]

Instead of reading points from a file and saving the X and Y components seperately, why not save them as a list of points?

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

You can just test the difference of all the points now, using the point member methods.

closest = mytestpoint.closestpoint(listofpoints)
print 'Closest point is at {0} and is a distance of {1} from {2}'.format(
    closest,
    mytestpoint.distanceto(closest),
    mytestpoint)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top