Skip to content

Instantly share code, notes, and snippets.

@matthewraaff
Created December 11, 2023 14:31
Show Gist options
  • Save matthewraaff/f128670bb2457a20bbc0f0bff6dfd92b to your computer and use it in GitHub Desktop.
Save matthewraaff/f128670bb2457a20bbc0f0bff6dfd92b to your computer and use it in GitHub Desktop.
Haversine function written in Python 3.12
from math import radians, sin, cos, tan, sqrt, atan2
RADIUS = 6356.752
class Coordinate():
def __init__(self, point_a: float, point_b: float):
self.a = point_a
self.b = point_b
def __repr__(self) -> str:
return "Coordinate<{0}, {1}>".format(
self.a,
self.b
)
def haversine(coord1: Coordinate, coord2: Coordinate) -> float:
pointone = (
radians(coord1.a),
radians(coord1.b)
)
pointtwo = (
radians(coord2.a),
radians(coord2.b)
)
deltaLat = pointtwo[0] - pointone[0]
deltaLon = pointtwo[1] - pointone[1]
a = sin(deltaLat/2) * sin(deltaLat/2) + \
cos(pointone[0]) * cos(pointtwo[0]) * \
sin(deltaLon/2) * sin(deltaLon/2)
c = 2 * atan2(sqrt(a), sqrt(1 - a))
return RADIUS * c # km
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment