Search code examples
javamathfloating-pointgpslatitude-longitude

How to precisely calculate distances in Java?


I'm using an implementation of this answer to calculate the distance between two points for my GPS tracking software.

However I've read on numerous StackOverFlow that using double is bad because of the inaccurate float representation of values. Therefore, I'm asking :

  • Would using BigDecimal to calculate distances be more accurate ?
  • Would converting the result from BigDecimal back to double produce additional inaccuracies ? (to store or retrieve the value)

Solution

  • No, using BigDecimal instead of double will not significantly improve the accuracy of this algorithm.

    The main source of error is a modeling error: you're using a formula that assumes the Earth is a perfect sphere. This means the result can be wrong by as much as 0.5%. The rounding error you get from using double is on the order of 0.000000000001%.

    To get more accurate results, you could use for example Vincenty's formulae, which assumes the Earth is an ellipsoid, but it is harder to implement than the great circle distance. To get even more accurate results, you should take into account the local topography, which is even harder.

    For further reading: https://en.m.wikipedia.org/wiki/Geographical_distance