Search code examples
pythonpython-3.xfor-loopwhile-looplogic

Finding minimum value of distance and returning from the function


I am trying to wrtie a simple python function which takes two 2-D points (one point is fixed and one is updating its position in the loop). The eucleadian distance is calculated in every itration and returns from the function when the distance calulated is minimum from the previous. (This requirement can be changed)

Here is what I tried:

x = 0
y = 0

fix_x = 5
fix_y = 5

//this will have some large value in the beginning
initial_disance = cal_distance(x, y, fix_x, fix_y)

def update_pose(x, y, fix_x, fix_y, initial_distance):
   
   while(x <= 10):
      
      while(y <= 10):
         
         current_dist = cal_distance(x, y, fix_x, fix_y)
         
         if(current_dist <= initial_distance):
            return current_distance
      y = y + 1
   
   x = x + 1
            

here I want to find x and y for which the distance is minimum. But this is iterating for only for one x value and exiting both the loops. I want it to carry out all the iterations and check for the minimum. How can I improve the code? :/ Thanks in advance :)


Solution

  • Fist you have to fix your comment (its # for python not //) and your indentation for the while loops.

    Secondly your loop reaches a return statement as soon as a calculated distance is shorter than the initial, which means your loops will be exited.

    Thirdly you are incrementing first the y value up to 10 and then the x value. I am not sure if this is intentional but this way you will not get all the possible permutations for x and y. Therefore i recomend using a nested for loop which iterates over y for every new x value.

    And lastly I am not sure if it is enough to return just the min distance or if it would be helpful to get the related coordinates with it.

    So here is my aproach for your function:

    def update_pose(x, y, fix_x, fix_y, initial_distance):
        min_dist = initial_distance
        coord = (x, y)
        for x_coord in range(x, 10):
            for y_coord in range(y, 10):
                current_dist = cal_distance(x_coord, y_coord, fix_x, fix_y)
                if current_dist < min_dist:
                    min_dist = current_dist  # every distance shorter than the initial one is saved
                    coord = (x_coord, y_coord)  # respective point is saved
        return min_dist, coord