1 回答

TA貢獻(xiàn)1786條經(jīng)驗(yàn) 獲得超11個(gè)贊
給定所需的輸出,可以通過不對(duì)haversine函數(shù)進(jìn)行向量化來避免錯(cuò)誤,因?yàn)檫@會(huì)將標(biāo)量傳遞給函數(shù)(如上面的注釋所述)。因此,您可以致電cdist:
import numpy as np
from scipy.spatial.distance import cdist
def haversine(x, y):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
print(type(x))
lat1, lon1 = np.radians(x)
lat2, lon2 = np.radians(y)
# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = np.sin(dlat/2)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2)**2
c = 2 * np.arcsin(np.sqrt(a))
r = 6371 # Radius of earth in kilometers. Use 3956 for miles
return c * r
gas_coords = np.array([[50, 80], [50, 81]])
postal_coords = np.array([[51, 80], [51, 81]])
cdist(postal_coords, gas_coords, metric=haversine)
添加回答
舉報(bào)