coderholic / django-cities

Countries and cities of the world for Django projects
MIT License
913 stars 377 forks source link

geo_distance crashes with specific coordinates #222

Open llybin opened 3 years ago

llybin commented 3 years ago
a = b = Point(113.9192428, 22.4876533)
a_y = radians(a.y)
b_y = radians(b.y)
delta_x = radians(a.x - b.x)
cos_x = sin(a_y) * sin(b_y) + cos(a_y) * cos(b_y) * cos(delta_x)
cos_x
1.0000000000000002

acos(cos_x) couldn't be higher 1

I fixed that:

def geo_distance(a, b):
    """
    Distance between two geo points in km. (p.x = long, p.y = lat)
    :param a: (Point)
    :param b: (Point)
    :return: float
    """
    if a == b:
        return 0.

    a_y = radians(a.y)
    b_y = radians(b.y)
    delta_x = radians(a.x - b.x)
    cos_x = sin(a_y) * sin(b_y) + cos(a_y) * cos(b_y) * cos(delta_x)
    # fix python float precision 1.0000000000000002
    cos_x = cos_x if cos_x < 1 else 1
    return acos(cos_x) * 6370.986  # PostGIS earth radius