为了账号安全,请及时绑定邮箱和手机立即绑定

函数认为我在浮动

函数认为我在浮动

宝慕林4294392 2021-04-09 16:27:34
我想计算两个数组中所有坐标对之间的距离。这是我写的一些代码: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 * rhaversine = np.vectorize(haversine)数组是gas_coords和postal_coords。注意type(postal_coords)>>>numpy.ndarraytype(gas_coords)>>>numpy.ndarray并且每个数组都有两列。当我尝试计算距离时using scipy.spatial.distance.cdist,出现以下错误:in haversine(x, y)      6     # convert decimal degrees to radians      7     print(type(x))---->; 8     lat1,lon1 =np.radians(x)      9     lat2,lon2 = np.radians(y)     10 TypeError: 'numpy.float64' object is not iterablehaversine似乎认为输入x是浮点数而不是数组。即使当我将数组传递给haversine类似haversine(np.zeros(2),np.zeros(2))的对象时,也会出现同样的问题。我应该注意,这仅在通过进行矢量化后发生np.vectorize。从来看haversine,参数不会以任何方式改变。是什么原因引起的错误?这是一个最小的工作示例:import numpy as npfrom scipy.spatial.distance import cdistgas_coords = np.array([[50, 80], [50, 81]])postal_coords = np.array([[51, 80], [51, 81]])cdist(postal_coords, gas_coords, metric = haversine)>>>array([[ 111.19492664,  131.7804742 ],          [ 131.7804742 ,  111.19492664]])
查看完整描述

1 回答

?
Qyouu

TA贡献1786条经验 获得超11个赞

给定所需的输出,可以通过不对haversine函数进行向量化来避免错误,因为这会将标量传递给函数(如上面的注释所述)。因此,您可以致电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)


查看完整回答
反对 回复 2021-04-27
  • 1 回答
  • 0 关注
  • 129 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号