0

I keep getting the following error with the code below: ValueError: math domain error. I can get the distance between two GPS points with other formulas but not with the formula below. Any help would be greatly appreciated,

Thanks,

Gavin

from math import radians, cos, sin, acos

#Formula below does not work :(

#JFK
lat1 = 40.639751
lon1 = -73.778925

#DUB
lat2 = 53.421333
lon2 = -6.270075

lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])

r = 6373
distance = acos((sin(lat1) * sin(lat2) + cos(lat1) * cos(lat2) * cos(lon1 - lon2)) * r)

print(distance)

3 Answers3

1

The formula is not correct. I believe the formula is acos(some_trig) * r and not acos(some_trig * r ) In conclusion

distance = acos((sin(lat1) * sin(lat2) + cos(lat1) * cos(lat2) * cos(lon1 - lon2))) * r
valentin
  • 3,498
  • 15
  • 23
  • 1
    Yes. First you calculate arc length between two points on a sphere and then you scale with sphere radius to obtain a distance – valentin Apr 13 '15 at 13:03
  • I apologize. Wikipedia backs up your math. https://en.wikipedia.org/wiki/Great-circle_distance – ArekBulski Apr 13 '15 at 13:07
0

This formula was posted on Calculating shortest path between 2 points on a flat map of the Earth and also look at https://en.wikipedia.org/wiki/Great-circle_distance

You multiply the values with r which tells acos to resolve 4435.6 into an angle which is absurd. Cosine could have never produced such a number, greater then 1.

Perhaps you should use put the angle given by acos into another formula for circle circumference.

from math import radians, cos, sin, acos, pi

#JFK
lat1 = 40.639751
lon1 = -73.778925

#DUB
lat2 = 53.421333
lon2 = -6.270075

lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])

r = 6373
d = acos((sin(lat1) * sin(lat2) + cos(lat1) * cos(lat2) * cos(lon1 - lon2)))
length = d * r

print(length)

5104.62871371

Community
  • 1
  • 1
ArekBulski
  • 4,520
  • 4
  • 39
  • 61
-1

The result of cos cannot be outside the [-1,1] range in real numbers, so the acos of a value outside that range is imaginary. However, you are multiplying by 6373, resulting in a value way outside [-1,1]. This is the reason for the error.

If you are trying to take the acos of a value outside [-1,1], you are either doing something wrong with your math, or you are looking for an imaginary result, in which case you should use the complex version of the acos, which is cmath.acos.

TheBlackCat
  • 9,791
  • 3
  • 24
  • 31