python - 使用特定经度和纬度计算距离时的值域误差

标签 python pandas function math

所以我使用了“https://gist.github.com/nickjevershed/6480846”上的距离函数,如下所示

def dist(lat1, long1, lat2, long2):

        # Convert latitude and longitude to 
        # spherical coordinates in radians.
        degrees_to_radians = math.pi/180.0

        # phi = 90 - latitude
        phi1 = (90.0 - lat1)*degrees_to_radians
        phi2 = (90.0 - lat2)*degrees_to_radians

        # theta = longitude
        theta1 = long1*degrees_to_radians
        theta2 = long2*degrees_to_radians

        # Compute spherical distance from spherical coordinates.

        # For two locations in spherical coordinates 
        # (1, theta, phi) and (1, theta, phi)
        # cosine( arc length ) = 
        #    sin phi sin phi' cos(theta-theta') + cos phi cos phi'
        # distance = rho * arc length

        cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) + 
               math.cos(phi1)*math.cos(phi2))
        arc = math.acos( cos )

        # Remember to multiply arc by the radius of the earth 
        # in your favorite set of units to get length.
        return arc * 3959

但是,当我尝试使用它来计算下面的值时,它给了我一个数学域错误。

    dist(47.62, 122.35, 47.62, 122.35)

    ---------------------------------------------------------------------------
    ValueError                                Traceback (most recent call last)
    <ipython-input-164-c70b6ce05167> in <module>()
    ----> 1 dist(47.62, 122.35, 47.62, 122.35)

    <ipython-input-78-5d1b406c1007> in dist(lat1, long1, lat2, long2)
         24     cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) + 
         25            math.cos(phi1)*math.cos(phi2))
    ---> 26     arc = math.acos( cos )
         27 
         28     # Remember to multiply arc by the radius of the earth

    ValueError: math domain

我尝试过其他值并且一切正常。我在距离函数中是否遗漏了一些隐藏逻辑,或者是否需要计算值?

最佳答案

问题在于您想要计算相同点之间的距离,因此结果应该为零。

但是由于舍入问题,您的值 cos > 1

这就是错误的原因。我建议您添加一个测试:

    # with your sample dist(47.62, 122.35, 47.62, 122.35)
    # cos = 1.0000000000000002, not good
    cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) + 
           math.cos(phi1)*math.cos(phi2))
    cos = min(cos,1.0) #to securise the value

在这种情况下,您等待的结果是:0.0

关于python - 使用特定经度和纬度计算距离时的值域误差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55205271/

相关文章:

python - 在Python中重新排序FFT

python - 如何在点击后删除 tkinter 中的消息

python - 当数据帧大小超过 100 行时,Pandas dataframe query() 会抛出错误

python - 如何将所有以前的值放入 pandas 数据框中的列中的列表中?

linux - Bash - 创建 'goto' 等价物的问题

python - 如果选择了另外两个 QCheckbox,则能够禁用 QCheckbox

python - Plone:如何更改原型(prototype)内容的所有权?

python - 合并列的重复单元格

通过更改 src 脚本文件的 Javascript 更新功能

c - 函数参数数据类型错误