距离计算不起作用

时间:2014-07-22 10:38:47

标签: python list math distance

使用Python,我正在尝试计算两点之间的距离,而我写的不起作用。 我有两个列表,每行有两个元素,有效的坐标列表,我正在尝试使用毕达哥拉斯来计算它们的分离,如果它们足够接近,则打印它们。 我有:

import math

for i in range(len(a)):           #a and c are imported lists
    for j in range(len(c)):
        y = b[i, 0] - d[j ,0]     #b and d are the actual lists, they have been cleaned up so they can be used
        z = b[i, 1] - d[j, 1]

        def f(y, z): (math.sqrt((y**2) + (z**2)))
        if f <= 0.0056:
            print i, j, b[i, 0], b[i, 1], d[j, 0], d[j, 1], f

谢谢!

2 个答案:

答案 0 :(得分:1)

有两个问题:

  • 你的功能不会返回任何内容
  • 你永远不会打电话给你。

使用def定义函数时,必须使用return返回结果:

def f(y, z): return math.sqrt(y**2 + z**2)

或者,在使用lambda时,return是隐含的:

f = lambda y, z: math.sqrt(y**2 + z**2)

然后,您仍需要调用该函数(f <= 0.0056将函数本身与数字进行比较)

dist = f(y, z)
if dist <= 0.0056:
        print i, j, b[i, 0], b[i, 1], d[j, 0], d[j, 1], dist

或者,由于您只使用此功能一次,只需完全删除功能定义:

 dist = math.sqrt(y**2 + z**2)
 if dist <= 0.0056:
     print i, j, b[i, 0], b[i, 1], d[j, 0], d[j, 1], dist

答案 1 :(得分:0)

鉴于此bd

b = ((1,1),(2,2))
d = ((1.001,1),(2,2))

以下代码:

import math
import itertools

for point_a, point_b in itertools.product(b, d):
    y = point_a[0] - point_b[0]
    z = point_a[1] - point_b[1]
    distance = math.sqrt((y**2) + (z**2))
    if distance < 0.0056:
        print "%s => %s: %s" % (point_a, point_b, distance)

输出:

(1, 1) => (1.001, 1): 0.001
(2, 2) => (2, 2): 0.0