[go: nahoru, domu]

Skip to content

Commit

Permalink
s2: Add LatLng.ApproxEqual.
Browse files Browse the repository at this point in the history
Add s1.Angle.ApproxEqual too.

Signed-off-by: David Symonds <dsymonds@golang.org>
  • Loading branch information
nes1983 authored and dsymonds committed Mar 19, 2020
1 parent 335b722 commit 9a88175
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 2 deletions.
7 changes: 6 additions & 1 deletion s1/angle.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ import (
//
// (60*Degree).Degrees() != 60
//
// When testing for equality, you should allow for numerical errors (floatApproxEq)
// When testing for equality, you should allow for numerical errors (ApproxEqual)
// or convert to discrete E5/E6/E7 values first.
type Angle float64

Expand Down Expand Up @@ -111,5 +111,10 @@ func (a Angle) String() string {
return strconv.FormatFloat(a.Degrees(), 'f', 7, 64) // like "%.7f"
}

// ApproxEqual reports whether the two angles are the same up to a small tolerance.
func (a Angle) ApproxEqual(other Angle) bool {
return math.Abs(float64(a)-float64(other)) <= epsilon
}

// BUG(dsymonds): The major differences from the C++ version are:
// - no unsigned E5/E6/E7 methods
6 changes: 6 additions & 0 deletions s2/latlng.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,3 +93,9 @@ func PointFromLatLng(ll LatLng) Point {
func LatLngFromPoint(p Point) LatLng {
return LatLng{latitude(p), longitude(p)}
}

// ApproxEqual reports whether the latitude and longitude of the two LatLngs
// are the same up to a small tolerance.
func (ll LatLng) ApproxEqual(other LatLng) bool {
return ll.Lat.ApproxEqual(other.Lat) && ll.Lng.ApproxEqual(other.Lng)
}
18 changes: 18 additions & 0 deletions s2/latlng_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -150,3 +150,21 @@ func TestLatLngDistance(t *testing.T) {
}
}
}

func TestLatLngApproxEqual(t *testing.T) {
const ε = epsilon / 10
tests := []struct {
a, b LatLng
want bool
}{
{LatLngFromDegrees(30, 50), LatLngFromDegrees(30, 50+ε), true},
{LatLngFromDegrees(30, 50), LatLngFromDegrees(30-ε, 50), true},
{LatLngFromDegrees(1, 5), LatLngFromDegrees(2, 3), false},
}

for _, test := range tests {
if got := test.a.ApproxEqual(test.b); got != test.want {
t.Errorf("%v.ApproxEqual(%v) = %t, want %t", test.a, test.b, got, test.want)
}
}
}
2 changes: 1 addition & 1 deletion s2/rect_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1108,7 +1108,7 @@ func TestDirectedHausdorffDistanceRectToRectDegenerateCases(t *testing.T) {
rectFromDegrees(-20, 95, 20, 105), rectFromDegrees(-30, 5, 30, 15))
}

func TestApproxEqual(t *testing.T) {
func TestRectApproxEqual(t *testing.T) {
// s1.Interval and r1.Interval have additional testing.

const ε = epsilon / 10
Expand Down

0 comments on commit 9a88175

Please sign in to comment.