gpt4 book ai didi

python - 函数认为我传递的是一个 float

转载 作者:太空宇宙 更新时间:2023-11-04 02:22:27 24 4
gpt4 key购买 nike

我想计算两个数组中所有坐标对之间的距离。这是我写的一些代码:

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

haversine = np.vectorize(haversine)

数组是gas_coordspostal_coords .请注意,

type(postal_coords)
>>>numpy.ndarray

type(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 iterable

haversine好像觉得输入x是 float 而不是数组。即使我将数组传递给 haversine喜欢haversine(np.zeros(2),np.zeros(2))出现同样的问题。我应该注意,这只发生在通过 np.vectorize 向量化之后.

从看haversine , 参数不会以任何方式改变。可能导致错误的原因是什么?

这是一个最小的工作示例:

import numpy as np
from scipy.spatial.distance import cdist

gas_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]])

最佳答案

给定所需的输出,可以通过不向量化 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)

关于python - 函数认为我传递的是一个 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51247168/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com