Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion area_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -308,8 +308,10 @@ func rotateHalfTurn(lng float64) float64 {
func assertRelClose(t *testing.T, got, want float64, label string) {
t.Helper()

// Every comparison against NaN is false, so test for it explicitly or a
// NaN result would pass.
const tol = 1e-9
if math.Abs(got-want) > tol*math.Max(1, math.Abs(want)) {
if math.IsNaN(got) || math.Abs(got-want) > tol*math.Max(1, math.Abs(want)) {
t.Fatalf("%s = %.17g, want %.17g", label, got, want)
}
}
4 changes: 4 additions & 0 deletions latlng.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,10 @@ func GreatCircleDistanceRads(a, b LatLng) float64 {

h := sinLat*sinLat + math.Cos(aLat)*math.Cos(bLat)*sinLng*sinLng

// Rounding can push h slightly above its mathematical maximum of 1 for
// antipodal points, and sqrt(1 - h) would then be NaN.
h = math.Min(h, 1)

return 2 * math.Atan2(math.Sqrt(h), math.Sqrt(1-h))
}

Expand Down
13 changes: 13 additions & 0 deletions latlng_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,19 @@ func TestGreatCircleDistance(t *testing.T) {
}
})

t.Run("antipodal", func(t *testing.T) {
t.Parallel()

// Rounding pushes the haversine term just above 1 for this pair, so an
// unclamped sqrt(1 - h) is NaN.
point := LatLng{Lat: 10.123456789, Lng: 20.987654321}
antipode := LatLng{Lat: -point.Lat, Lng: point.Lng - piDeg}

assertRelClose(t, GreatCircleDistanceRads(point, antipode), math.Pi, "rads")
assertRelClose(t, GreatCircleDistanceKm(point, antipode), math.Pi*earthRadiusKm, "km")
assertRelClose(t, GreatCircleDistanceM(point, antipode), math.Pi*earthRadiusKm*1000, "m")
})

t.Run("symmetric", func(t *testing.T) {
t.Parallel()

Expand Down
Loading