Skip to content

Commit

Permalink
Normalize longitude without looping (#460)
Browse files Browse the repository at this point in the history
* Normalize longitude without looping

Change normalizeLongitude to remove loops. Returned value is a normalized longitude in range [-180;+180)
  • Loading branch information
bocops authored Nov 15, 2021
1 parent 604ed00 commit 6707912
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -665,13 +665,16 @@ private static double clipLatitude(double latitude) {
}

private static double normalizeLongitude(double longitude) {
while (longitude < -LONGITUDE_MAX) {
longitude = longitude + LONGITUDE_MAX * 2;
if (longitude >= -LONGITUDE_MAX && longitude < LONGITUDE_MAX) {
// longitude is within proper range, no normalization necessary
return longitude;
}
while (longitude >= LONGITUDE_MAX) {
longitude = longitude - LONGITUDE_MAX * 2;
}
return longitude;

// % in Java uses truncated division with the remainder having the same sign as
// the dividend. For any input longitude < -360, the result of longitude%CIRCLE_DEG
// will still be negative but > -360, so we need to add 360 and apply % a second time.
final long CIRCLE_DEG = 2 * LONGITUDE_MAX; // 360 degrees
return (longitude % CIRCLE_DEG + CIRCLE_DEG + LONGITUDE_MAX) % CIRCLE_DEG - LONGITUDE_MAX;
}

/**
Expand Down
15 changes: 13 additions & 2 deletions test_data/encoding.csv
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,25 @@
1,1,11,6FH32222+222
################################################################################
#
# Special cases over 90 latitude and 180 longitude
# Special cases over 90 latitude
#
################################################################################
90,1,4,CFX30000+
92,1,4,CFX30000+
90,1,10,CFX3X2X2+X2
################################################################################
#
# Special cases with longitude needing normalization (<< -180 or >> +180)
#
################################################################################
1,180,4,62H20000+
1,181,4,62H30000+
90,1,10,CFX3X2X2+X2
20.3701135,362.78223535156,13,7FG49QCJ+2VXGJ
47.0000625,728.0000625,10,8FVC2222+22
-41.2730625,1254.7859375,10,4VCPPQGP+Q9
20.3701135,-357.217764648,13,7FG49QCJ+2VXGJ
47.0000625,-711.9999375,10,8FVC2222+22
-41.2730625,-905.2140625,10,4VCPPQGP+Q9
################################################################################
#
# Test non-precise latitude/longitude value
Expand Down

0 comments on commit 6707912

Please sign in to comment.