找到距离的最小值并从函数返回

问题描述 投票:0回答:2

我正在尝试编写一个简单的 python 函数,该函数需要两个 2-D 点(一个点是固定的,一个点正在更新其在循环中的位置)。欧氏距离在每次迭代中计算,并在计算出的距离与前一次相比最小时从函数返回。 (此要求可以更改)

这是我尝试过的:

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
            

这里我想找到距离最小的 x 和 y。但这只是迭代一个 x 值并退出两个循环。我希望它执行所有迭代并检查最小值。我该如何改进代码? :/ 提前致谢:)

python python-3.x for-loop while-loop logic
2个回答
1
投票

首先你必须修正你的注释(它是Python的#而不是//)和while循环的缩进。

其次,一旦计算出的距离短于初始距离,循环就会到达 return 语句,这意味着循环将退出。

第三,您首先将 y 值增加到 10,然后将 x 值增加。我不确定这是否是故意的,但这样您将无法获得 x 和 y 的所有可能排列。因此,我建议使用嵌套的 for 循环,它针对每个新的 x 值迭代 y。

最后,我不确定仅返回最小距离是否足够,或者是否有助于获取相关坐标。

所以这是我对您的功能的处理方法:

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

1
投票

基本上,一旦该值小于初始值,您就会返回该值。

如果您想要最小可能值,那么您还需要一个变量来跟踪迄今为止的最小值并迭代所有值以检查当前值是否小于最小值。 所有计算完成后返回。

x = 0
y = 0

fix_x = 5
fix_y = 5

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

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

          y += 1

       x += 1

    return minimum_distance
© www.soinside.com 2019 - 2024. All rights reserved.