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)
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
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
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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.