Skip to content

Commit

Permalink
Use hypot in haversine calculation for better accuracy
Browse files Browse the repository at this point in the history
hypot(x, y) is sqrt(x^2 + y^2) but implemented in an error-corrected way.  It is a bit slower though, so depends on the tradeoff you want to make.  Feel free to accept or reject.
  • Loading branch information
asinghvi17 authored Oct 29, 2024
1 parent 35c6d0d commit b1f6556
Showing 1 changed file with 3 additions and 2 deletions.
5 changes: 3 additions & 2 deletions src/haversine.jl
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,11 @@ function (dist::Haversine)(x, y)
Δφ = φ₂ - φ₁ # latitudes

# haversine formula
a = sind(Δφ/2)^2 + cosd(φ₁)*cosd(φ₂)*sind(Δλ/2)^2
# hypot(x, y) is equivalent to sqrt(x^2 + y^2)
sqrt_a = hypot(sind(Δφ/2), cosd(φ₁)*cosd(φ₂)*sind(Δλ/2))

# distance on the sphere
2 * (dist.radius * asin( min(a, one(a)) )) # take care of floating point errors
2 * (dist.radius * asin( min(sqrt_a, one(sqrt_a)) )) # take care of floating point errors
end

haversine(x, y, radius::Number=6_371_000) = Haversine(radius)(x, y)
Expand Down

0 comments on commit b1f6556

Please sign in to comment.