Skip to content

Commit

Permalink
Optimize distance calculation by getting rid of rounding
Browse files Browse the repository at this point in the history
  • Loading branch information
TheMarex committed Apr 26, 2018
1 parent 7414e22 commit b813444
Showing 1 changed file with 20 additions and 11 deletions.
31 changes: 20 additions & 11 deletions src/util/coordinate_calculation.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -27,26 +27,34 @@ class CheapRulerContainer
public:
CheapRulerContainer(const int number_of_rulers)
: cheap_ruler_cache(number_of_rulers, mapbox::cheap_ruler::CheapRuler(0)),
step(90.0 / number_of_rulers)
step(90.0 * COORDINATE_PRECISION / number_of_rulers)
{
for (int n = 0; n < number_of_rulers; n++)
{
cheap_ruler_cache[n] = mapbox::cheap_ruler::CheapRuler(
step * (n + 0.5), mapbox::cheap_ruler::CheapRuler::Meters);
step * (n + 0.5) / COORDINATE_PRECISION, mapbox::cheap_ruler::CheapRuler::Meters);
}
};
mapbox::cheap_ruler::CheapRuler &getRuler(const double lat)

mapbox::cheap_ruler::CheapRuler &getRuler(const FixedLatitude lat_1, const FixedLatitude lat_2)
{
return cheap_ruler_cache[std::min((int)std::floor(abs(lat) / step),
(int)cheap_ruler_cache.size() - 1)];
auto lat = (lat_1 + lat_2) / util::FixedLatitude{2};
return getRuler(lat);
}

mapbox::cheap_ruler::CheapRuler &getRuler(const FixedLatitude lat)
{
BOOST_ASSERT(step > 1);
auto bin = (std::abs(static_cast<int>(lat)) - 1) / step;
return cheap_ruler_cache[bin];
};

private:
std::vector<mapbox::cheap_ruler::CheapRuler> cheap_ruler_cache;
const double step;
const int step;
};
CheapRulerContainer cheap_ruler_container(1800);
}
} // namespace

// Does not project the coordinates!
std::uint64_t squaredEuclideanDistance(const Coordinate lhs, const Coordinate rhs)
Expand All @@ -72,7 +80,8 @@ double fccApproximateDistance(const Coordinate coordinate_1, const Coordinate co
const auto lat1 = static_cast<double>(util::toFloating(coordinate_1.lat));
const auto lon2 = static_cast<double>(util::toFloating(coordinate_2.lon));
const auto lat2 = static_cast<double>(util::toFloating(coordinate_2.lat));
return cheap_ruler_container.getRuler(0.5 * (lat1 + lat2)).distance({lon1, lat1}, {lon2, lat2});
return cheap_ruler_container.getRuler(coordinate_1.lat, coordinate_2.lat)
.distance({lon1, lat1}, {lon2, lat2});
}

double haversineDistance(const Coordinate coordinate_1, const Coordinate coordinate_2)
Expand Down Expand Up @@ -466,6 +475,6 @@ double computeArea(const std::vector<Coordinate> &polygon)
return area / 2.;
}

} // ns coordinate_calculation
} // ns util
} // ns osrm
} // namespace coordinate_calculation
} // namespace util
} // namespace osrm

0 comments on commit b813444

Please sign in to comment.