calculating distance between two coordinate arrays python

时间:2018-03-25 19:32:19

标签: python arrays

I have an array of 4 coordinates in each array

x0 = [1,2,3,4] #x_coordinates
y0 = [1,2,3,4] #y_coordinates

x1 = [11,12,13,14] #x_coordinates
y1 = [11,12,13,14] #y_coordinates

I would like to find the distance between the two coordinates.

distance = sqrt((x1 - x0)^2 + (y1 - y0)^2)

So, I tried

distance = math.sqrt((x1 - x0)**2 + (y1 - y0)**2)

But the error is TypeError: only length-1 arrays can be converted to Python scalars.

Isnt it possible to do an element wise operation by just using the array_variable? Or do I have to iterate it by using a for loop?

I found this as a probable answer, but looks quite complicated with numpy. calculating distance between two numpy arrays

EDIT:

Tried the following

x_dist = pow((x1 - x0), 2)
y_dist = pow((y1 - y0), 2)
dist = x_dist+y_dist
dist=dist**2

2 个答案:

答案 0 :(得分:1)

Yes, with plain python lists you have to use a loop or comprehension to do things element-wise.

It's not complicated with numpy, you just have to wrap each list in an array:

from numpy import array, sqrt

x0 = array([1, 2, 3, 4])  # x_coordinates
y0 = array([1, 2, 3, 4])  # y_coordinates

x1 = array([11, 12, 13, 14])  # x_coordinates
y1 = array([11, 12, 13, 14])  # y_coordinates

print(sqrt((x1 - x0) ** 2 + (y1 - y0) ** 2))

Here is how to do it in plain Python using a loop comprehension:

from math import sqrt

x0_list = [1, 2, 3, 4]  # x_coordinates
y0_list = [1, 2, 3, 4]  # y_coordinates

x1_list = [11, 12, 13, 14]  # x_coordinates
y1_list = [11, 12, 13, 14]  # y_coordinates

print([sqrt((x1 - x0) ** 2 + (y1 - y0) ** 2)
       for x0, y0, x1, y1 in zip(x0_list, y0_list, x1_list, y1_list)])

答案 1 :(得分:0)

With out numpy, this could be used:

import math

def func(x0,x1,y0,y1):

    distance = []

    for a,b,c,d in zip(x0,x1,y0,y1):
        result = math.sqrt((b - a)**2 + (d - c)**2)
        distance.append(result)

    return distance

x0 = [1,2,3,4] #x_coordinates
y0 = [1,2,3,4] #y_coordinates

x1 = [11,12,13,14] #x_coordinates
y1 = [11,12,13,14] #y_coordinates

print(func(x0, x1, y0, y1))