Ошибка области значений при расчете расстояния с использованием определенной долготы и широты - PullRequest
1 голос
/ 17 марта 2019

Так что я использовал функцию расстояния, найденную в "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

Я пробовал другие значения и все работает нормально. Есть ли какая-то скрытая логика, которую я пропустил в функции расстояния или есть требование для вычисляемых значений?

1 Ответ

0 голосов
/ 17 марта 2019

проблема возникает из-за того, что вы хотите вычислить расстояние между одними и теми же точками, чтобы результат был равен нулю.

, но с проблемой округления у вас есть значение 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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...