You are on page 1of 3

Haversine function

Ioannis Chalidis
23rd November 2014

Haversine Function.

The haversine function is a trigonometric function defined by:


 
1
1
1
2
hav(z) = vers(z) = (1 cos (z)) = sin
z
2
2
2

and the inverse haversine function is: hav 1 (z) = 2 sin1 ( z) or:

hav 1 (z) = 2 arcsin z

M.Sc. Univ. of Sheffield, UK

Figure 1: A sphere with radius r and two points A,B.

Haversine Formula

The haversine formula is an equation important in navigation, giving greatcircle distances between two points on a sphere from their longitudes and
latitudes. The distance between two points: A(a1 , b1 ), B(a2 , b2 ), in a sphere
(earth) with radius r is given by the formula:
 
d
= hav (a2 a1 ) + cos (a1 ) cos (a2 ) hav (b2 b1 )
hav
r
It is important to note that latitudes:a1 , a2 and longitudes: b1 , b2 are in radian. One can then solve for d either by simply applying the inverse haversine
(if available) or by using the arcsin (inverse sine) function:
d = r hav 1 (hav (a2 a1 ) + cos (a1 ) cos (a2 ) hav (b2 b1 ))
and finally1 :
s
d = 2r arcsin

sin2 (a2 a1 )
sin2 (b2 b1 )

+ cos (a1 ) cos (a2 )


2
2

R-code

The following R-programm computes the distance between pairs of points


on the surface of a sphere (earth).

#function to calculate the distance between


#
#two points given latitude and longitude
#
earth.distIC <- function(lat1, lat2, long1, long2)
{
R <- 6371
#mean radius of the earth in km
#we need to convert latitudes and
#longitudes from degrees to radians
1

Note that hav 1 ( hav(x) ) = x. for every x belongs to the domain of hav.

lat1 <- lat1 * 2 * pi / 360


lat2 <- lat2 * 2 * pi / 360
long1 <- long1 * 2 * pi / 360
long2 <- long2 * 2 * pi / 360
#spherical coordinates
y1=((sin(lat1-lat2))^2)/2
y2=((sin(long1-long2))^2)/2
invhav<-2*asin(sqrt(y1+cos(lat1)*cos(lat2)*y2))
R * invhav
}
#end of function earth.distIC
#CALCULATE THE longitude and latitude
x<-stations$V5+stations$V6/60
y<-stations$V8+stations$V9/60
# #CALCULATE THE DISTANCE MATRIX
N<-384^2
dist.matrix<-matrix(1:N,nrow=384,byrow=T)
for (i in 1:384)
{
for (j in 1:384)
{
dist.matrix[i,j]=earth.distIC(x[i],x[j],y[i],y[j])
}
}
x<-stations$V5+stations$V6/60
y<-stations$V8+stations$V9/60
dist.matrix<-matrix(1:N,nrow=384,byrow=T)
for (i in 1:384)
{
for (j in 1:384)
{
dist.matrix[i,j]=earth.distIC(x[i],x[j],y[i],y[j])
}
}
#END OF CALCULATING DISTANCE MATRIX

You might also like