Skip to content

geo_distance crashes with specific coordinates #222

@llybin

Description

@llybin
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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions