Haversine formula: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
(→‎{{header|Commodore BASIC}}: Move to correct alphabetical location.)
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(35 intermediate revisions by 19 users not shown)
Line 54:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F haversine(=lat1, lon1, =lat2, lon2)
V r = 6372.8
V dLat = radians(lat2 - lat1)
Line 64:
R r * c
 
print(haversine(36.12, -86.67, 33.94, -118.40))</langsyntaxhighlight>
 
{{out}}
Line 72:
 
=={{header|ABAP}}==
<langsyntaxhighlight lang="abap">
DATA: X1 TYPE F, Y1 TYPE F,
X2 TYPE F, Y2 TYPE F, YD TYPE F,
Line 95:
 
WRITE : 'Distance between given points = ' , distance , 'km .' .
</syntaxhighlight>
</lang>
 
{{out}}
Line 103:
 
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO;
with Ada.Long_Float_Text_IO; use Ada.Long_Float_Text_IO;
with Ada.Numerics.Generic_Elementary_Functions;
Line 133:
DMS_To_Radians (33.0, 56.4), DMS_To_Radians (118.0, 24.0)), -- Los Angeles International Airport (LAX)
Aft=>3, Exp=>0);
end Haversine_Formula;</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
Line 140:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-2.3.5 algol68g-2.3.5].}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of '''format'''[ted] ''transput''.}}
'''File: Haversine_formula.a68'''<langsyntaxhighlight lang="algol68">#!/usr/local/bin/a68g --script #
 
REAL r = 20 000/pi + 6.6 # km #,
Line 161:
# Americans don't know kilometers #
printf(($"dist: "g(0,1)" km ("g(0,1)" mi.)"l$, d, d / 1.609344))
)</langsyntaxhighlight>
{{out}}
<pre>
Line 170:
{{Trans|ALGOL 68}}
Using the mean radius value suggested in the task.
<langsyntaxhighlight lang="algolw">begin % compute the distance between places using the Haversine formula %
real procedure arcsin( real value x ) ; arctan( x / sqrt( 1 - ( x * x ) ) );
real procedure distance ( real value th1Deg, ph1Deg, th2Deg, ph2Deg ) ;
Line 192:
writeon( i_w := 4, s_w := 0, "distance: ", mi, " km (", km, " mi.)" )
end
end.</langsyntaxhighlight>
{{out}}
<pre>
distance: 2886 km (1794 mi.)
</pre>
 
=={{header|Amazing Hopper}}==
{{Trans|Python}}
<syntaxhighlight lang="c">
 
/* fórmula de Haversine para distancias en una
superficie esférica */
 
#include <basico.h>
 
#define MIN 60
#define SEG 3600
#define RADIO 6372.8
#define UNAMILLA 1.609344
 
algoritmo
números ( lat1, lon1, lat2, lon2, dlat, dlon, millas )
si ' total argumentos es (9) ' // LAT1 M LON1 M LAT2 M LON2 M
#basic{ lat1 = narg(2) + narg(3)/MIN
lon1 = narg(4) + narg(5)/MIN
lat2 = narg(6) + narg(7)/MIN
lon2 = narg(8) + narg(9)/MIN }
sino si ' total argumentos es (13) ' // LAT1 M LON1 M S LAT2 M LON2 M S
#basic{ lat1 = narg(2) + narg(3)/MIN + narg(4)/SEG
lon1 = narg(5) + narg(6)/MIN + narg(7)/SEG
lat2 = narg(8) + narg(9)/MIN + narg(10)/SEG
lon2 = narg(11) + narg(12)/MIN + narg(13)/SEG }
sino
imprimir("Modo de uso:\ndist.bas La1 M [S] Lo1 M [S] La2 M [S] Lo2 M [S]\n")
término prematuro
fin si
 
#basic{
dlat = sin(radian(lat2 - lat1)/2)^2
dlon = sin(radian(lon2 - lon1)/2)^2
RADIO*(2*arc sin(sqrt(dlat + cos(radian(lat1)) * cos(radian(lat2)) * dlon )))
}
---copiar en 'millas'---, " km. (",millas,dividido por (UNA MILLA)," mi.)\n"
decimales '2', imprimir
terminar
</syntaxhighlight>
{{out}}
<pre>
$ hopper3 basica/dist.bas -x -o bin/dist
Generating binary ‘bin/dist’...Ok!
Symbols: 27
Total size: 0.75 Kb
$ ./bin/dist 36 7.2 86 40.2 33 56.4 118 24
2887.26 km. (1794.06 mi.)
</pre>
 
=={{header|AMPL}}==
<syntaxhighlight lang="ampl">
<lang AMPL>
set location;
set geo;
Line 221 ⟶ 276:
 
printf "The distance between the two points is approximately %f km.\n", dist['BNA','LAX'];
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 228 ⟶ 283:
 
=={{header|APL}}==
<langsyntaxhighlight lang="apl">r←6371
hf←{(p q)←○⍺ ⍵÷180 ⋄ 2×rׯ1○(+/(2*⍨1○(p-q)÷2)×1(×/2○⊃¨p q))*÷2}
36.12 ¯86.67 hf 33.94 ¯118.40</langsyntaxhighlight>
{{out}}
<pre>2886.44</pre>
Line 240 ⟶ 295:
Here we reach through a foreign function interface to a temporary instance of a JavaScript interpreter.
 
<langsyntaxhighlight lang="applescript">use AppleScript version "2.4" -- Yosemite (10.10) or later
use framework "Foundation"
use framework "JavaScriptCore"
Line 341 ⟶ 396:
missing value
end if
end sqrt</langsyntaxhighlight>
{{Out}}
<pre>2887.26</pre>
Line 347 ⟶ 402:
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">radians: function [x]-> x * pi // 180
 
haversine: function [src,tgt][
Line 360 ⟶ 415:
]
 
print haversine @[36.12 neg 86.67] @[33.94, neg 118.40]</langsyntaxhighlight>
 
{{out}}
Line 367 ⟶ 422:
 
=={{header|ATS}}==
<syntaxhighlight lang="ats">
<lang ATS>
#include
"share/atspre_staload.hats"
Line 404 ⟶ 459:
$extfcall(void, "printf", "dist: %.1f km (%.1f mi.)\n", d, d / 1.609344)
end // end of [main0]
</syntaxhighlight>
</lang>
 
{{out}}
Line 412 ⟶ 467:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">MsgBox, % GreatCircleDist(36.12, 33.94, -86.67, -118.40, 6372.8, "km")
 
GreatCircleDist(La1, La2, Lo1, Lo2, R, U) {
Line 424 ⟶ 479:
Rad(Deg) {
return, Deg * 4 * ATan(1) / 180
}</langsyntaxhighlight>
{{out}}
<pre>2887.259951 km</pre>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f HAVERSINE_FORMULA.AWK
# converted from Python
Line 448 ⟶ 503:
return degree * (3.1415926 / 180.)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>distance: 2887.2599 km</pre>
<pre>
distance: 2887.2599 km
</pre>
 
 
=={{header|BASIC}}==
==={{header|Applesoft BASIC}}===
<lang basic>
{{works with|Chipmunk Basic}}
{{works with|GW-BASIC}}
{{works with|Minimal BASIC}}
{{works with|MSX BASIC}}
{{trans|Commodore BASIC}}
<syntaxhighlight lang="qbasic">100 HOME : rem 100 CLS for GW-BASIC and MSX BASIC : DELETE for Minimal BASIC
110 LET P = ATN(1)*4
120 LET D = P/180
130 LET M = 36.12
140 LET K = -86.67
150 LET N = 33.94
160 LET L = -118.4
170 LET R = 6372.8
180 PRINT " DISTANCIA DE HAVERSINE ENTRE BNA Y LAX = ";
190 LET A = SIN((L-K)*D/2)
200 LET A = A*A
210 LET B = COS(M*D)*COS(N*D)
220 LET C = SIN((N-M)*D/2)
230 LET C = C*C
240 LET D = SQR(C+B*A)
250 LET E = D/SQR(1-D*D)
260 LET F = ATN(E)
270 PRINT 2*R*F;"KM"
280 END</syntaxhighlight>
 
==={{header|BASIC256}}===
<syntaxhighlight lang="basic256">
global radioTierra # radio de la tierra en km
radioTierra = 6372.8
 
function Haversine(lat1, long1, lat2, long2 , radio)
d_long = radians(long1 - long2)
theta1 = radians(lat1)
theta2 = radians(lat2)
dx = cos(d_long) * cos(theta1) - cos(theta2)
dy = sin(d_long) * cos(theta1)
dz = sin(theta1) - sin(theta2)
return asin(sqr(dx*dx + dy*dy + dz*dz) / 2) * radio * 2
end function
 
print
print " Distancia de Haversine entre BNA y LAX = ";
print Haversine(36.12, -86.67, 33.94, -118.4, radioTierra); " km"
end
</syntaxhighlight>
{{out}}
<pre> Distancia de Haversine entre BNA y LAX = 2887.25994877 km.</pre>
 
==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
<syntaxhighlight lang="qbasic">100 cls
110 pi = arctan(1)*4 : rem define pi = 3.1415...
120 deg2rad = pi/180 : rem define grados a radianes 0.01745..
130 lat1 = 36.12
140 long1 = -86.67
150 lat2 = 33.94
160 long2 = -118.4
170 radio = 6372.8
180 print " Distancia de Haversine entre BNA y LAX = ";
190 d_long = deg2rad*(long1-long2)
200 theta1 = deg2rad*(lat1)
210 theta2 = deg2rad*(lat2)
220 dx = cos(d_long)*cos(theta1)-cos(theta2)
230 dy = sin(d_long)*cos(theta1)
240 dz = sin(theta1)-sin(theta2)
250 print (asin(sqr(dx*dx+dy*dy+dz*dz)/2)*radio*2);"km"
260 end</syntaxhighlight>
 
==={{header|Gambas}}===
<syntaxhighlight lang="vbnet">Public deg2rad As Float = Pi / 180 ' define grados a radianes 0.01745..
Public radioTierra As Float = 6372.8 ' radio de la tierra en km
 
Public Sub Main()
Print "\n Distancia de Haversine entre BNA y LAX = "; Haversine(36.12, -86.67, 33.94, -118.4, radioTierra); " km"
End
 
Function Haversine(lat1 As Float, long1 As Float, lat2 As Float, long2 As Float, radio As Float) As Float
Dim d_long As Float = deg2rad * (long1 - long2)
Dim theta1 As Float = deg2rad * lat1
Dim theta2 As Float = deg2rad * lat2
Dim dx As Float = Cos(d_long) * Cos(theta1) - Cos(theta2)
Dim dy As Float = Sin(d_long) * Cos(theta1)
Dim dz As Float = Sin(theta1) - Sin(theta2)
 
Return ASin(Sqr(dx * dx + dy * dy + dz * dz) / 2) * radio * 2
 
End Function</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
 
==={{header|GW-BASIC}}===
{{works with|Applesoft BASIC}}
{{works with|BASICA}}
{{works with|Chipmunk Basic}}
{{works with|MSX BASIC}}
{{works with|Minimal BASIC}}
{{works with|PC-BASIC|any}}
{{trans|Commodore BASIC}}
<syntaxhighlight lang="qbasic">100 CLS : rem 100 HOME for Applesoft BASIC : DELETE for Minimal BASIC
110 LET P = ATN(1)*4
120 LET D = P/180
130 LET M = 36.12
140 LET K = -86.67
150 LET N = 33.94
160 LET L = -118.4
170 LET R = 6372.8
180 PRINT " DISTANCIA DE HAVERSINE ENTRE BNA Y LAX = ";
190 LET A = SIN((L-K)*D/2)
200 LET A = A*A
210 LET B = COS(M*D)*COS(N*D)
220 LET C = SIN((N-M)*D/2)
230 LET C = C*C
240 LET D = SQR(C+B*A)
250 LET E = D/SQR(1-D*D)
260 LET F = ATN(E)
270 PRINT 2*R*F;"KM"
280 END</syntaxhighlight>
 
==={{header|Minimal BASIC}}===
{{works with|Applesoft BASIC}}
{{works with|Chipmunk Basic}}
{{works with|GW-BASIC}}
{{works with|MSX BASIC}}
{{trans|Commodore BASIC}}
<syntaxhighlight lang="qbasic">110 LET P = ATN(1)*4
120 LET D = P/180
130 LET M = 36.12
140 LET K = -86.67
150 LET N = 33.94
160 LET L = -118.4
170 LET R = 6372.8
180 PRINT " DISTANCIA DE HAVERSINE ENTRE BNA Y LAX = ";
190 LET A = SIN((L-K)*D/2)
200 LET A = A*A
210 LET B = COS(M*D)*COS(N*D)
220 LET C = SIN((N-M)*D/2)
230 LET C = C*C
240 LET D = SQR(C+B*A)
250 LET E = D/SQR(1-D*D)
260 LET F = ATN(E)
270 PRINT 2*R*F;"KM"
280 END</syntaxhighlight>
 
==={{header|MSX Basic}}===
The [[#GW-BASIC|GW-BASIC]] solution works without any changes.
 
==={{header|QBasic}}===
{{works with|QBasic|1.1}}
{{works with|QuickBasic|4.5}}
<syntaxhighlight lang="basic">
CONST pi = 3.141593 ' define pi
CONST radio = 6372.8 ' radio de la tierra en km
Line 475 ⟶ 680:
Haversine! = (SQR(dx! * dx! + dy! * dy! + dz! * dz!) / 2) * radio * 2
END FUNCTION</syntaxhighlight>
</lang>
{{out}}
<pre> Distancia de Haversine: 2862.63 km</pre>
<pre>
Distancia de Haversine: 2862.63 km
</pre>
 
==={{header|Quite BASIC}}===
<syntaxhighlight lang="qbasic">100 CLS
110 LET p = atan(1)*4
120 LET d = p/180
130 LET k = 36.12
140 LET m = -86.67
150 LET l = 33.94
160 LET n = -118.4
170 LET r = 6372.8
180 PRINT " Distancia de Haversine entre BNA y LAX = ";
190 LET g = d*(m-n)
200 LET t = d*(k)
210 LET s = d*(l)
220 LET x = COS(g)*COS(t)-COS(s)
230 LET y = SIN(g)*COS(t)
240 LET z = SIN(t)-SIN(s)
250 PRINT (ASIN(SQR(x*x+y*y+z*z)/2)*r*2);"km"
260 END</syntaxhighlight>
 
==={{header|BASIC256True BASIC}}===
<syntaxhighlight lang="basic">DEF Haversine (lat1, long1, lat2, long2)
<lang BASIC256>
OPTION ANGLE RADIANS
global radioTierra # radio de la tierra en km
LET R = 6372.8 !radio terrestre en km.
radioTierra = 6372.8
LET dLat = RAD(lat2-lat1)
LET dLong = RAD(long2-long1)
LET lat1 = RAD(lat1)
LET lat2 = RAD(lat2)
LET Haversine = R *2 * ASIN(SQR(SIN(dLat/2)^2 + SIN(dLong/2)^2 *COS(lat1) * COS(lat2)))
END DEF
PRINT
 
functionPRINT "Distancia de Haversine:"; Haversine(lat136.12, long1-86.67, lat233.94, long2 , radio-118.4); "km"
END</syntaxhighlight>
d_long = radians(long1 - long2)
theta1 = radians(lat1)
theta2 = radians(lat2)
dx = cos(d_long) * cos(theta1) - cos(theta2)
dy = sin(d_long) * cos(theta1)
dz = sin(theta1) - sin(theta2)
return asin(sqr(dx*dx + dy*dy + dz*dz) / 2) * radio * 2
end function
 
print
print " Distancia de Haversine entre BNA y LAX = ";
print Haversine(36.12, -86.67, 33.94, -118.4, radioTierra); " km"
end
</lang>
{{out}}
<pre>Distancia de Haversine: 2887.26 km</pre>
<pre>
Distancia de Haversine entre BNA y LAX = 2887.25994877 km.
</pre>
 
==={{header|Yabasic}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="yabasic">//pi está predefinido en Yabasic
deg2rad = pi / 180 // define grados a radianes 0.01745..
radioTierra = 6372.8 // radio de la tierra en km
 
sub Haversine(lat1, long1, lat2, long2 , radio)
d_long = deg2rad * (long1 - long2)
theta1 = deg2rad * lat1
theta2 = deg2rad * lat2
dx = cos(d_long) * cos(theta1) - cos(theta2)
dy = sin(d_long) * cos(theta1)
dz = sin(theta1) - sin(theta2)
return asin(sqr(dx*dx + dy*dy + dz*dz) / 2) * radio * 2
end sub
 
print " Distancia de Haversine entre BNA y LAX = ", Haversine(36.12, -86.67, 33.94, -118.4, radioTierra), " km"
end</syntaxhighlight>
{{out}}
<pre> Distancia de Haversine entre BNA y LAX = 259.478 km</pre>
 
=={{header|BBC BASIC}}==
Line 513 ⟶ 745:
Uses BBC BASIC's '''MOD(array())''' function which calculates
the square-root of the sum of the squares of the elements of an array.
<langsyntaxhighlight lang="bbcbasic"> PRINT "Distance = " ; FNhaversine(36.12, -86.67, 33.94, -118.4) " km"
END
Line 521 ⟶ 753:
\ SINRAD(e1-e2) * COSRAD(n1), \
\ SINRAD(n1) - SINRAD(n2)
= ASN(MOD(d()) / 2) * 6372.8 * 2</langsyntaxhighlight>
{{out}}
<pre>
Line 534 ⟶ 766:
… supplied with a small POSIX shell wrapper to feed the arguments to <code>bc</code>. ([https://edugit.org/-/snippets/27 see also])
 
<syntaxhighlight lang="sh">
<lang sh>
#!/bin/sh
#-
Line 619 ⟶ 851:
 
# output is in metres, rounded to millimetres, error < ¼% in WGS84
</syntaxhighlight>
</lang>
{{out}}
<pre>$ sh dist.sh 36.12 -86.67 33.94 -118.4
Line 626 ⟶ 858:
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <math.h>
Line 651 ⟶ 883:
 
return 0;
}</langsyntaxhighlight>
 
=={{header|c sharp|C#}}==
{{trans|Groovy}}
<langsyntaxhighlight lang="csharp">public static class Haversine {
public static double calculate(double lat1, double lon1, double lat2, double lon2) {
var R = 6372.8; // In kilometers
Line 678 ⟶ 910:
 
// Returns: The distance between coordinates 36.12,-86.67 and 33.94,-118.4 is: 2887.25995060711
</syntaxhighlight>
</lang>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">
#define _USE_MATH_DEFINES
 
Line 738 ⟶ 970:
return 0;
}
</syntaxhighlight>
</lang>
 
=={{header|clojure|Clojure}}==
{{trans|Java}}
<langsyntaxhighlight lang="clojure">
(defn haversine
[{lon1 :longitude lat1 :latitude} {lon2 :longitude lat2 :latitude}]
Line 755 ⟶ 987:
(haversine {:latitude 36.12 :longitude -86.67} {:latitude 33.94 :longitude -118.40})
;=> 2887.2599506071106
</syntaxhighlight>
</lang>
 
=={{header|CoffeeScript}}==
{{trans|JavaScript}}
<langsyntaxhighlight lang="coffee">haversine = (args...) ->
R = 6372.8; # km
radians = args.map (deg) -> deg/180.0 * Math.PI
Line 768 ⟶ 1,000:
R * 2 * Math.asin(Math.sqrt(a))
 
console.log haversine(36.12, -86.67, 33.94, -118.40)</langsyntaxhighlight>
{{out}}
<pre>2887.2599506071124</pre>
 
=={{header|Commodore BASIC}}==
 
PETSCII has the pi symbol <tt>π</tt> in place of the ASCII tilde <tt>~</tt>; Commodore BASIC interprets this symbol as the mathematical constant.
 
<syntaxhighlight lang="basic">10 REM================================
15 REM HAVERSINE FORMULA
20 REM
25 REM 2021-09-24
30 REM EN.WIKIPEDIA.ORG/WIKI/HAVERSINE_FORMULA
35 REM
40 REM C64 HAS PI CONSTANT
45 REM X1 LONGITUDE 1
50 REM Y1 LATITUDE 1
55 REM X2 LONGITUDE 2
60 REM Y2 LATITUDE 2
65 REM
70 REM V1, 2021-10-02, ALVALONGO
75 REM ===============================
100 REM MAIN
105 DR=π/180:REM DEGREES TO RADIANS
110 PRINT CHR$(147);CHR$(5);"HAVERSINE FORMULA"
120 PRINT "GREAT-CIRCLE DISTANCE"
130 R=6372.8:REM AVERAGE EARTH RADIUS IN KILOMETERS
200 REM GET DATA
210 PRINT
220 INPUT "LONGITUDE 1=";X1
230 INPUT "LATITUDE 1=";Y1
240 PRINT
250 INPUT "LONGITUDE 2=";X2
260 INPUT "LATITUDE 2=";Y2
270 GOSUB 500
280 PRINT
290 PRINT "DISTANCE=";D;"KM"
300 GET K$:IF K$="" THEN 300
310 GOTO 210
490 END
500 REM HAVERSINE FORMULA ------------
520 A=SIN((X2-X1)*DR/2)
530 A=A*A
540 B=COS(Y1*DR)*COS(Y2*DR)
550 C=SIN((Y2-Y1)*DR/2)
560 C=C*C
570 D=SQR(C+B*A)
580 E=D/SQR(1-D*D)
590 F=ATN(E)
600 D=2*R*F
610 RETURN</syntaxhighlight>
{{Out}}
<pre>HAVERSINE FORMULA
GREAT-CIRCLE DISTANCE
 
LONGITUDE 1=? -86.67
LATITUDE 1=? 36.12
 
LONGITUDE 2=? -118.40
LATITUDE 2=? 33.94
 
DISTANCE= 2887.25995 KM</pre>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defparameter *earth-radius* 6372.8)
 
(defparameter *rad-conv* (/ pi 180))
Line 793 ⟶ 1,084:
(deg->rad lng1)
(deg->rad lat2)
(deg->rad lng2)))</langsyntaxhighlight>
{{out}}
<pre>CL-USER> (format t "~%The distance between BNA and LAX is about ~$ km.~%"
Line 799 ⟶ 1,090:
 
The distance between BNA and LAX is about 2887.26 km.</pre>
 
 
=={{header|Crystal}}==
{{trans|Python}}
<langsyntaxhighlight lang="ruby">include Math
def haversine(lat1, lon1, lat2, lon2)
Line 820 ⟶ 1,110:
 
puts "distance is #{haversine(36.12, -86.67, 33.94, -118.40)} km "
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 827 ⟶ 1,117:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.math;
 
real haversineDistance(in real dth1, in real dph1,
Line 850 ⟶ 1,140:
writefln("Haversine distance: %.1f km",
haversineDistance(36.12, -86.67, 33.94, -118.4));
}</langsyntaxhighlight>
{{out}}
<pre>Haversine distance: 2887.3 km</pre>
Line 857 ⟶ 1,147:
An alternate direct implementation of the haversine formula as shown at [[wp:Haversine formula|wikipedia]]. The same length, but perhaps a little more clear about what is being done.
 
<langsyntaxhighlight lang="d">import std.stdio, std.math;
 
real toRad(in real degrees) pure nothrow @safe @nogc {
Line 883 ⟶ 1,173:
greatCircleDistance(36.12, -86.67, 33.94, -118.4,
earthRadius));
}</langsyntaxhighlight>
{{out}}
<pre>Great circle distance: 2887.3 km
Line 890 ⟶ 1,180:
=={{header|Dart}}==
{{trans|Java}}
<langsyntaxhighlight lang="dart">import 'dart:math';
 
class Haversine {
Line 913 ⟶ 1,203:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>2887.2599506071106</pre>
 
=={{header|Delphi}}==
<langsyntaxhighlight lang="delphi">program HaversineDemo;
uses Math;
 
Line 937 ⟶ 1,227:
begin
Writeln('Haversine distance: ', HaversineDist(36.12, -86.67, 33.94, -118.4):7:2, ' km.');
end.</langsyntaxhighlight>
{{out}}
<pre>Haversine distance: 2887.26 km.</pre>
 
=={{header|EasyLang}}==
{{trans|C}}
<syntaxhighlight>
func dist th1 ph1 th2 ph2 .
r = 6371
ph1 -= ph2
dz = sin th1 - sin th2
dx = cos ph1 * cos th1 - cos th2
dy = sin ph1 * cos th1
return 2 * r * pi / 180 * asin (sqrt (dx * dx + dy * dy + dz * dz) / 2)
.
print dist 36.12 -86.67 33.94 -118.4
</syntaxhighlight>
 
=={{header|Elena}}==
ELENA 4.x:
<langsyntaxhighlight lang="elena">import extensions;
import system'math;
Line 964 ⟶ 1,268:
console.printLineFormatted("The distance between coordinates {0},{1} and {2},{3} is: {4}", 36.12r, -86.67r, 33.94r, -118.40r,
Haversine(36.12r, -86.67r, 33.94r, -118.40r))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 971 ⟶ 1,275:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Haversine do
@v :math.pi / 180
@r 6372.8 # km for the earth radius
Line 984 ⟶ 1,288:
bna = {36.12, -86.67}
lax = {33.94, -118.40}
IO.puts Haversine.distance(bna, lax)</langsyntaxhighlight>
 
{{out}}
Line 993 ⟶ 1,297:
=={{header|Elm}}==
 
<langsyntaxhighlight lang="elm">haversine : ( Float, Float ) -> ( Float, Float ) -> Float
haversine ( lat1, lon1 ) ( lat2, lon2 ) =
let
Line 1,019 ⟶ 1,323:
[ Html.text (toString (haversine ( 36.12, -86.67 ) ( 33.94, -118.4 )))
]
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,026 ⟶ 1,330:
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">% Implementer by Arjun Sunel
-module(haversine).
-export([main/0]).
Line 1,043 ⟶ 1,347:
C = 2 * math:asin(math:sqrt(A)),
R*C.
</syntaxhighlight>
</lang>
{{out}}
<pre>2887.2599506071106
Line 1,049 ⟶ 1,353:
 
=={{header|ERRE}}==
<langsyntaxhighlight ERRElang="erre">% Implemented by Claudio Larini
 
PROGRAM HAVERSINE_DEMO
Line 1,080 ⟶ 1,384:
PRINT("HAVERSINE DISTANCE: ";RES;" KM.")
END PROGRAM
</syntaxhighlight>
</lang>
Using double-precision variables output is 2887.260209071741 km, while using single-precision variable output is 2887.261 Km.
 
Line 1,116 ⟶ 1,420:
 
{{Works with|Office 365 betas 2021}}
<langsyntaxhighlight lang="lisp">HAVERSINE
=LAMBDA(lla,
LAMBDA(llb,
Line 1,141 ⟶ 1,445:
)
)
)</langsyntaxhighlight>
Each of the two arguments in the example below is an Excel dynamic array of two adjacent values. The # character yields a reference to the array with the given top-left grid address.
 
Line 1,185 ⟶ 1,489:
=={{header|F_Sharp|F#}}==
{{trans|Go}} using units of measure
<langsyntaxhighlight lang="fsharp">open System
 
[<Measure>] type deg
Line 1,209 ⟶ 1,513:
let main argv =
printfn "%A" (hsDist (pos(36.12<deg>, -86.67<deg>)) (pos(33.94<deg>, -118.40<deg>)))
0</langsyntaxhighlight>
{{out}}
<pre>2887.259951</pre>
Line 1,215 ⟶ 1,519:
=={{header|Factor}}==
{{trans|J}}
<langsyntaxhighlight lang="factor">USING: arrays kernel math math.constants math.functions math.vectors sequences ;
 
: haversin ( x -- y ) cos 1 swap - 2 / ;
Line 1,225 ⟶ 1,529:
2bi
v.
haversininv R_earth * ;</langsyntaxhighlight>
<langsyntaxhighlight lang="factor">( scratchpad ) { 36.12 -86.67 } { 33.94 -118.4 } haversineDist .
2887.259950607113</langsyntaxhighlight>
 
=={{header|FBSL}}==
Based on the Fortran and Groovy versions.
<langsyntaxhighlight lang="qbasic">#APPTYPE CONSOLE
 
PRINT "Distance = ", Haversine(36.12, -86.67, 33.94, -118.4), " km"
Line 1,246 ⟶ 1,550:
RETURN radius * c
END FUNCTION
</syntaxhighlight>
</lang>
{{out}}
Distance = 2887.25995060711 km
Press any key to continue...
 
=={{header|FOCAL}}==
{{trans|ZX Spectrum Basic}}
<syntaxhighlight lang="focal">1.01 S BA = 36.12; S LA = -86.67
1.02 S BB = 33.94; S LB = -118.4
1.03 S DR = 3.1415926536 / 180; S D = 2 * 6372.8
1.04 S TA = (LB - LA) * DR
1.05 S TB = DR * BA
1.06 S TC = DR * BB
1.07 S DZ = FSIN(TB) - FSIN(TC)
1.08 S DX = FCOS(TA) * FCOS(TB) - FCOS(TC)
1.09 S DY = FSIN(TA) * FCOS(TB)
1.10 S AS = DX * DX + DY * DY + DZ * DZ
1.11 S AS = FSQT(AS) / 2
1.12 S HDIST = D * FATN(AS / FSQT(1 - AS^2))
1.13 T %6.2,"Haversine distance ",HDIST,!</syntaxhighlight>
{{output}}
<pre>Haversine distance = 2887.26</pre>
Note that FOCAL lacks a built-in arcsine function, but appendix D of the FOCAL manual shows how to compute it using arctangent and square root instead.
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: s>f s>d d>f ;
: deg>rad 174532925199433e-16 f* ;
: difference f- deg>rad 2 s>f f/ fsin fdup f* ;
Line 1,266 ⟶ 1,589:
;
 
36.12e -86.67e 33.94e -118.40e haversine cr f.</langsyntaxhighlight>
{{out}}
<pre>
Line 1,273 ⟶ 1,596:
 
=={{header|Fortran}}==
<syntaxhighlight lang="fortran">
<lang Fortran>
program example
implicit none
Line 1,308 ⟶ 1,631:
 
end program example
</syntaxhighlight>
</lang>
 
=={{header|Free Pascal}}==
Here is a Free Pascal version, works in most Pascal dialects, but also note the Delphi entry that also works in Free Pascal.
<langsyntaxhighlight lang="pascal">program HaversineDemo;
uses
Math;
Line 1,328 ⟶ 1,651:
begin
Writeln('Haversine distance between BNA and LAX: ', HaversineDistance(36.12, -86.67, 33.94, -118.4):7:2, ' km.');
end.</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' version 09-10-2016
' compile with: fbc -s console
 
Line 1,366 ⟶ 1,689:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre> Haversine distance between BNA and LAX = 2887.259950607111 km.</pre>
 
=={{header|Frink}}==
Frink has built-in constants for the radius of the earth, whether it is the mean radius <CODE>earthradius</CODE>, the equatorial radius <CODE>earthradius_equatorial</CODE>, or the polar radius <CODE>earthradius_polar</CODE>. Below calculates the distance between the points using the haversine formula on a sphere using the mean radius, but we can do better:
<lang frink>
<syntaxhighlight lang="frink">haversine[theta] := (1-cos[theta])/2
 
dist[lat1, long1, lat2, long2] := 2 earthradius arcsin[sqrt[haversine[lat2-lat1] + cos[lat1] cos[lat2] haversine[long2-long1]]]
 
d = dist[36.12 deg, -86.67 deg, 33.94 deg, -118.40 deg]
println[d-> "km"]</syntaxhighlight>
 
</lang>
{{out}}
<pre>
2886.4489734366999158 km
</pre>
 
Note that physical constants like degrees, kilometers, and the average radius of the earth (as well as the polar and equatorial radii) are already known to Frink. Also note that units of measure are tracked throughout all calculations, and results can be displayed in a huge number of units of distance (miles, km, furlongs, chains, feet, statutemiles, etc.) by changing the final <code>"km"</code> to something like <code>"miles"</code>.
 
However, Frink's library/sample program [http://futureboy.us/fsp/colorize.fsp?fileName=navigation.frink navigation.frink] (included in larger distributions) contains a much higher-precision calculation that uses ellipsoidal (not spherical) calculations to determine the distance on earth's geoid with far greater accuracy:.
 
The calculations are due to:
<lang frink>
 
use navigation.frink
"Direct and Inverse Solutions of Geodesics on the Ellipsoid with Application
of Nested Equations", T.Vincenty, ''Survey Review XXII'', 176, April 1975.
http://www.ngs.noaa.gov/PUBS_LIB/inverse.pdf
 
There is also a slightly higher-accuracy algorithm (closer to nanometers instead of fractions of millimeters LOL):
"Algorithms for geodesics", Charles F. F. Karney, ''Journal of Geodesy'', January 2013, Volume 87, Issue 1, pp 43-55
http://link.springer.com/article/10.1007%2Fs00190-012-0578-z
 
<syntaxhighlight lang="frink">use navigation.frink
 
d = earthDistance[36.12 deg North, 86.67 deg West, 33.94 deg North, 118.40 deg West]
println[d-> "km"]</syntaxhighlight>
 
</lang>
{{out}}
<pre>
2892.7769573807044975 km
</pre>
 
Which should be treated as the closest-to-right answer for the actual distance on the earth's geoid, based on the WGS84 geoid datum.
 
=={{header|FunL}}==
<langsyntaxhighlight lang="funl">import math.*
 
def haversin( theta ) = (1 - cos( theta ))/2
Line 1,403 ⟶ 1,746:
2R asin( sqrt(h) )
 
println( haversine((36.12, -86.67), (33.94, -118.40)) )</langsyntaxhighlight>
 
{{out}}
Line 1,416 ⟶ 1,759:
 
Since it was trivial, this functions returns the distance in miles and kilometers.
<langsyntaxhighlight lang="futurebasic">window 1
include "ConsoleWindow"
 
local fn Haversine( lat1 as double, lon1 as double, lat2 as double, lon2 as double, miles as ^double, kilometers as ^double )
dim as double deg2rad, dLat, dLon, a, c, earth_radius_miles, earth_radius_kilometers
 
earth_radius_miles = 3959.0 // Radius of the Earth in miles
earth_radius_kilometers = 6372.8 // Radius of the Earth in kilometers
deg2rad = Pi / 180 // Pi is predefined in FutureBasic
earth_radius_miles = 3959.0 // Radius of the Earth in miles
dLat = deg2rad * ( lat2 - lat1 )
earth_radius_kilometers = 6372.8 // Radius of the Earth in kilometers
dLon = deg2rad * ( lon2 - lon1 )
deg2rad = Pi / 180 // Pi is predefined in FutureBasic
a = sin( dLat / 2 ) * sin( dLat / 2 ) + cos( deg2rad * lat1 ) * cos( deg2rad * lat2 ) * sin( dLon / 2 ) * sin( dLon / 2 )
c = 2 * asin( sqr(a) )
dLat = deg2rad * ( lat2 - lat1 )
 
dLon = deg2rad * ( lon2 - lon1 )
miles.nil# = earth_radius_miles * c
a = sin( dLat / 2 ) * sin( dLat / 2 ) + cos( deg2rad * lat1 ) * cos( deg2rad * lat2 ) * sin( dLon / 2 ) * sin( dLon / 2 )
kilometers.nil# = earth_radius_kilometers * c
c = 2 * asin( sqr(a) )
miles.nil# = earth_radius_miles * c
kilometers.nil# = earth_radius_kilometers * c
end fn
 
dim as double miles, kilometers
 
fn Haversine( 36.12, -86.67, 33.94, -118.4, @miles, @kilometers )
 
Line 1,441 ⟶ 1,784:
print "Distance in kilometers between BNA LAX: "; using "####.####"; kilometers; " km."
 
HandleEvents</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,449 ⟶ 1,792:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,478 ⟶ 1,821:
func main() {
fmt.Println(hsDist(degPos(36.12, -86.67), degPos(33.94, -118.40)))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,485 ⟶ 1,828:
 
=={{header|Groovy}}==
<langsyntaxhighlight Groovylang="groovy">def haversine(lat1, lon1, lat2, lon2) {
def R = 6372.8
// In kilometers
Line 1,500 ⟶ 1,843:
haversine(36.12, -86.67, 33.94, -118.40)
 
> 2887.25995060711</langsyntaxhighlight>
 
=={{header|Haskell}}==
<langsyntaxhighlight Haskelllang="haskell">import DataControl.BifunctorMonad (bimapjoin)
import Data.Bifunctor (bimap)
import Text.Printf (printf)
 
-------------------- HAVERSINE FORMULA -------------------
 
-- The haversine of an angle.
Line 1,513 ⟶ 1,859:
-- between two points on Earth.
-- The latitude and longtitude are assumed to be in degrees.
greatCircleDistance ::
earthDist :: (Float, Float) -> (Float, Float) -> Float
(Float, Float) ->
earthDist = distDeg 6371
(Float, Float) ->
Float
greatCircleDistance = distDeg 6371
where
distDeg radius p1 p2 =
Line 1,533 ⟶ 1,882:
)
)
deg2rad = join bimap d2r((/ 180) . (pi d2r*))
where
d2r = (/ 180) . (pi *)
 
--------------------------- TEST -------------------------
main :: IO ()
main =
printf
"The distance between BNA and LAX is about %0.f km.\n"
(earthDistgreatCircleDistance bna lax)
where
bna = (36.12, -86.67)
lax = (33.94, -118.40)</langsyntaxhighlight>
{{Out}}
<pre>The distance between BNA and LAX is about 2886 km.</pre>
Line 1,550 ⟶ 1,898:
=={{header|Icon}} and {{header|Unicon}}==
{{trans|C}}
<langsyntaxhighlight Iconlang="icon">link printf
 
procedure main() #: Haversine formula
Line 1,564 ⟶ 1,912:
dy := sin(a[2]) * cos(a[1])
return asin(sqrt(dx * dx + dy * dy + dz * dz) / 2) * 2 * 6371
end</langsyntaxhighlight>
 
{{libheader|Icon Programming Library}}
Line 1,574 ⟶ 1,922:
=={{header|Idris}}==
{{trans|Haskell}}
<langsyntaxhighlight Idrislang="idris">module Main
-- The haversine of an angle.
Line 1,614 ⟶ 1,962:
dst : Double
dst = earthDist bna lax
</syntaxhighlight>
</lang>
{{out}}
<pre>The distance between BNA and LAX is about 2887 km.</pre>
 
=={{header|IS-BASIC}}==
<langsyntaxhighlight ISlang="is-BASICbasic">100 PROGRAM "Haversine.bas"
110 PRINT "Haversine distance:";HAVERSINE(36.12,-86.67,33.94,-118.4);"km"
120 DEF HAVERSINE(LAT1,LON1,LAT2,LON2)
Line 1,627 ⟶ 1,975:
160 LET LAT1=RAD(LAT1):LET LAT2=RAD(LAT2)
170 LET HAVERSINE=R*2*ASIN(SQR(SIN(DLAT/2)^2+SIN(DLON/2)^2*COS(LAT1)*COS(LAT2)))
190 END DEF</langsyntaxhighlight>
 
=={{header|J}}==
'''Solution:'''
<langsyntaxhighlight lang="j">require 'trig'
haversin=: 0.5 * 1 - cos
Rearth=: 6372.8
haversineDist=: Rearth * haversin^:_1@((1 , *&(cos@{.)) +/ .* [: haversin -)&rfd
</syntaxhighlight>
</lang>
Note: J derives the inverse haversin ( <code>haversin^:_1</code> )
from the definition of haversin.
 
'''Example Use:'''
<langsyntaxhighlight lang="j"> 36.12 _86.67 haversineDist 33.94 _118.4
2887.26</langsyntaxhighlight>
 
=={{header|Java}}==
{{trans|Groovy}}
<langsyntaxhighlight lang="java">public class Haversine {
public static final double R = 6372.8; // In kilometers
 
public static double haversine(double lat1, double lon1, double lat2, double lon2) {
double dLat = Math.toRadians(lat2 - lat1);
double dLon = Math.toRadians(lon2 - lon1);
lat1 = Math.toRadians(lat1);
lat2 = Math.toRadians(lat2);
double dLat = lat2 - lat1;
double dLon = Math.toRadians(lon2 - lon1);
 
double a = Math.pow(Math.sin(dLat / 2), 2) + Math.pow(Math.sin(dLon / 2), 2) * Math.cos(lat1) * Math.cos(lat2);
double c = 2 * Math.asin(Math.sqrt(a));
return R * c;
}
 
public static void main(String[] args) {
System.out.println(haversine(36.12, -86.67, 33.94, -118.40));
}
}</langsyntaxhighlight>
{{out}}
<pre>2887.2599506071106</pre>
Line 1,667 ⟶ 2,017:
===ES5===
{{trans|Java}}
<langsyntaxhighlight lang="javascript">function haversine() {
var radians = Array.prototype.map.call(arguments, function(deg) { return deg/180.0 * Math.PI; });
var lat1 = radians[0], lon1 = radians[1], lat2 = radians[2], lon2 = radians[3];
Line 1,677 ⟶ 2,027:
return R * c;
}
console.log(haversine(36.12, -86.67, 33.94, -118.40));</langsyntaxhighlight>
{{out}}
<pre>2887.2599506071124</pre>
 
===ES6===
<langsyntaxhighlight JavaScriptlang="javascript">((x, y) => {
'use strict';
 
Line 1,718 ⟶ 2,068:
// --> 2887.26
 
})([36.12, -86.67], [33.94, -118.40]);</langsyntaxhighlight>
{{Out}}
<pre>2887.26</pre>
 
=={{header|jq}}==
<langsyntaxhighlight lang="jq">def haversine(lat1;lon1; lat2;lon2):
def radians: . * (1|atan)/45;
def sind: radians|sin;
Line 1,731 ⟶ 2,081:
(((lat2 - lat1)/2) | sind | sq) as $dlat
| (((lon2 - lon1)/2) | sind | sq) as $dlon
| 2 * 6372.8 * (( $dlat + (lat1|cosd) * (lat2|cosd) * $dlon ) | sqrt | asin) ;</langsyntaxhighlight>
'''Example''':
haversine(36.12; -86.67; 33.94; -118.4)
Line 1,738 ⟶ 2,088:
=={{header|Jsish}}==
From Javascript, ES5, except the ''arguments'' value is an Array in jsish, not an Object.
<langsyntaxhighlight lang="javascript">/* Haversine formula, in Jsish */
function haversine() {
var radians = arguments.map(function(deg) { return deg/180.0 * Math.PI; });
Line 1,756 ⟶ 2,106:
haversine(36.12, -86.67, 33.94, -118.40) ==> 2887.259950607112
=!EXPECTEND!=
*/</langsyntaxhighlight>
 
{{out}}
Line 1,765 ⟶ 2,115:
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">haversine(lat1, lon1, lat2, lon2) =
2 * 6372.8 * asin(sqrt(sind((lat2 - lat1) / 2) ^ 2 +
cosd(lat1) * cosd(lat2) * sind((lon2 - lon1) / 2) ^ 2))
 
@show haversine(36.12, -86.67, 33.94, -118.4)</langsyntaxhighlight>
 
{{out}}
Line 1,777 ⟶ 2,127:
{{trans|Groovy}}
Use Unicode characters.
<langsyntaxhighlight lang="scala">import java.lang.Math.*
 
const val R = 6372.8 // in kilometers
Line 1,789 ⟶ 2,139:
}
 
fun main(args: Array<String>) = println("result: " + haversine(36.12, -86.67, 33.94, -118.40))</langsyntaxhighlight>
 
=={{header|Lambdatalk}}==
{{trans|Python}}
<syntaxhighlight lang="scheme">
{def haversine
{def diameter {* 6372.8 2}}
{def radians {lambda {:a} {* {/ {PI} 180} :a}}}
{lambda {:lat1 :lon1 :lat2 :lon2}
{let { {:dLat {radians {- :lat2 :lat1}}}
{:dLon {radians {- :lon2 :lon1}}}
{:lat1 {radians :lat1}}
{:lat2 {radians :lat2}}
} {* {diameter}
{asin {sqrt {+ {pow {sin {/ :dLat 2}} 2}
{* {cos :lat1}
{cos :lat2}
{pow {sin {/ :dLon 2}} 2} }}}}}}}}
-> haversine
 
{haversine 36.12 -86.67 33.94 -118.40}
-> 2887.2599506071106
 
or, using
 
{def deg2dec
{lambda {:s :w}
{let { {:s {if {or {W.equal? :s W}
{W.equal? :s S}} then - else +}}
{:dm {S.replace ° by space in
{S.replace ' by in :w}}}
} :s{S.get 0 :dm}.{round {* {/ 100 60} {S.get 1 :dm}}}}}}
-> deg2dec
 
we can just write
 
{haversine
{deg2dec N 36°7.2'}
{deg2dec W 86°40.2'}
{deg2dec N 33°56.4'}
{deg2dec W 118°24.0'}}
-> 2887.2599506071106
 
</syntaxhighlight>
 
=={{header|Liberty BASIC}}==
<langsyntaxhighlight lang="lb">print "Haversine distance: "; using( "####.###########", havDist( 36.12, -86.67, 33.94, -118.4)); " km."
end
function havDist( th1, ph1, th2, ph2)
Line 1,804 ⟶ 2,197:
dy = sin( LgD) * cos( th1)
havDist = asn( ( dx^2 +dy^2 +dz^2)^0.5 /2) *diameter
end function</langsyntaxhighlight>
<pre>Haversine distance: 2887.25995060711 km.</pre>
 
=={{header|LiveCode}}==
<langsyntaxhighlight LiveCodelang="livecode">function radians n
return n * (3.1415926 / 180)
end radians
Line 1,834 ⟶ 2,227:
return (radiusEarth * (2.0 * asin(sqrt(haver))))
end haversine</langsyntaxhighlight>
Test
<langsyntaxhighlight LiveCodelang="livecode">haversine(36.12, -86.67, 33.94, -118.40)
2887.259923</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">local function haversine(x1, y1, x2, y2)
r=0.017453292519943295769236907684886127;
x1= x1*r; x2= x2*r; y1= y1*r; y2= y2*r; dy = y2-y1; dx = x2-x1;
a = math.pow(math.sin(dx/2),2) + math.cos(x1) * math.cos(x2) * math.pow(math.sin(dy/2),2); c = 2 * math.asin(math.sqrt(a)); d = 6372.8 * c;
return d;
end</langsyntaxhighlight>
Usage:
<langsyntaxhighlight lang="lua">print(haversine(36.12, -86.67, 33.94, -118.4));</langsyntaxhighlight>
Output:
<pre>2887.2599506071</pre>
Line 1,853 ⟶ 2,246:
=={{header|Maple}}==
Inputs assumed to be in radians.
<langsyntaxhighlight Maplelang="maple">distance := (theta1, phi1, theta2, phi2)->2*6378.14*arcsin( sqrt((1-cos(theta2-theta1))/2 + cos(theta1)*cos(theta2)*(1-cos(phi2-phi1))/2) );</langsyntaxhighlight>
If you prefer, you can define a haversine function to clarify the definition:<langsyntaxhighlight Maplelang="maple">haversin := theta->(1-cos(theta))/2;
distance := (theta1, phi1, theta2, phi2)->2*6378.14*arcsin( sqrt(haversin(theta2-theta1) + cos(theta1)*cos(theta2)*haversin(phi2-phi1)) );</langsyntaxhighlight>
 
Usage:
Line 1,864 ⟶ 2,257:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Inputs assumed in degrees. Sin and Haversine expect arguments in radians; the built-in variable 'Degree' converts from degrees to radians.
<syntaxhighlight lang="mathematica">
<lang Mathematica>
distance[{theta1_, phi1_}, {theta2_, phi2_}] :=
2*6378.14 ArcSin@
Sqrt[Haversine[(theta2 - theta1) Degree] +
Cos[theta1*Degree] Cos[theta2*Degree] Haversine[(phi2 - phi1) Degree]]
</syntaxhighlight>
</lang>
Usage:
<pre>distance[{36.12, -86.67}, {33.94, -118.4}]</pre>
Line 1,877 ⟶ 2,270:
=={{header|MATLAB}} / {{header|Octave}}==
 
<langsyntaxhighlight Matlablang="matlab">function rad = radians(degree)
% degrees to radians
rad = degree .* pi / 180;
Line 1,893 ⟶ 2,286:
end;
 
[a,c,dlat,dlon] = haversine(36.12,-86.67,33.94,-118.40); % BNA to LAX</langsyntaxhighlight>
{{out}}
<pre>distance: 2887.2600 km</pre>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">dms(d, m, s) := (d + m/60 + s/3600)*%pi/180$
 
great_circle_distance(lat1, long1, lat2, long2) :=
Line 1,909 ⟶ 2,302:
great_circle_distance(dms( 36, 7, 28.10), -dms( 86, 40, 41.50),
dms( 33, 56, 32.98), -dms(118, 24, 29.05)), numer;
/* 2886.326609413624 */</langsyntaxhighlight>
 
=={{header|МК-61/52}}==
<syntaxhighlight lang="text">П3 -> П2 -> П1 -> П0
пи 1 8 0 / П4
ИП1 МГ ИП3 МГ - ИП4 * П1 ИП0 МГ ИП4 * П0 ИП2 МГ ИП4 * П2
Line 1,918 ⟶ 2,311:
ИП1 cos ИП0 cos * ИП2 cos - П6
ИП1 sin ИП0 cos * П7
ИП6 x^2 ИП7 x^2 ИП8 x^2 + + КвКор 2 / arcsin 2 * ИП5 * С/П</langsyntaxhighlight>
 
''Input'': 6371,1 as a radius of the Earth, taken as the ball, or 6367,554 as an average radius of the Earth, or 6367,562 as an approximation of the radius of the average circumference (by Krasovsky's ellipsoid) to Р5; В/О ''lat<sub>1</sub>'' С/П ''long<sub>1</sub>'' С/П ''lat<sub>2</sub>'' С/П ''long<sub>2</sub>'' С/П; the coordinates must be entered as ''degrees,minutes'' (example: 46°50' as 46,5).
Line 1,933 ⟶ 2,326:
 
=={{header|MySQL}}==
<langsyntaxhighlight MySQLlang="mysql">DELIMITER $$
 
CREATE FUNCTION haversine (
Line 1,958 ⟶ 2,351:
END$$
 
DELIMITER ;</langsyntaxhighlight>
 
Usage:
Line 1,966 ⟶ 2,359:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import std/math
 
proc radianshaversine(x):lat1, floatlon1, =lat2, xlon2: *float): Pifloat / 180=
 
proc haversine(lat1, lon1, lat2, lon2): float =
const r = 6372.8 # Earth radius in kilometers
let
dLat = radiansdegToRad(lat2 - lat1)
dLon = radiansdegToRad(lon2 - lon1)
lat1 = radiansdegToRad(lat1)
lat2 = radiansdegToRad(lat2)
 
a = sin(dLat / 2) * sin(dLat / 2) + cos(lat1) * cos(lat2) * sin(dLon / 2) * sin(dLon / 2)
c = 2 * arcsin(sqrt(a))
 
result = r * c
 
echo haversine(36.12, -86.67, 33.94, -118.40)</langsyntaxhighlight>
{{out}}
<pre>22887.8872599506071115e+03259950607111</pre>
 
=={{header|Oberon-2}}==
Works with oo2c version2
<langsyntaxhighlight lang="oberon2">
MODULE Haversines;
IMPORT
Line 2,017 ⟶ 2,408:
Out.LongRealFix(Distance(36.12,-86.67,33.94,-118.4),6,10);Out.Ln
END Haversines.
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,024 ⟶ 2,415:
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
bundle Default {
class Haversine {
Line 2,045 ⟶ 2,436:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,052 ⟶ 2,443:
 
=={{header|Objective-C}}==
<langsyntaxhighlight lang="objc">+ (double) distanceBetweenLat1:(double)lat1 lon1:(double)lon1
lat2:(double)lat2 lon2:(double)lon2 {
//degrees to radians
Line 2,068 ⟶ 2,459:
double R = 6372.8;
return R * c;
}</langsyntaxhighlight>
 
=={{header|OCaml}}==
Line 2,075 ⟶ 2,466:
but with an eye toward generality and reuse,
this is how I might start:
<langsyntaxhighlight lang="ocaml">(* Preamble -- some math, and an "angle" type which might be part of a common library. *)
let pi = 4. *. atan 1.
let radians_of_degrees = ( *. ) (pi /. 180.)
Line 2,106 ⟶ 2,497:
and lax = LatLong.of_angles (Deg 33.94) (Deg (-118.4))
in
earth_dist bna lax;;</langsyntaxhighlight>
 
If the above is fed to the REPL, the last line will produce this:
Line 2,116 ⟶ 2,507:
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">import: math
 
: haversine(lat1, lon1, lat2, lon2)
Line 2,127 ⟶ 2,518:
lat 2 / sin sq + sqrt asin 2 * 6372.8 * ;
 
haversine(36.12, -86.67, 33.94, -118.40) println</langsyntaxhighlight>
 
{{out}}
Line 2,137 ⟶ 2,528:
{{trans|REXX}}
The rxmath library provides the required functions.
<langsyntaxhighlight lang="oorexx">/*REXX pgm calculates distance between Nashville & Los Angles airports. */
say " Nashville: north 36º 7.2', west 86º 40.2' = 36.12º, -86.67º"
say "Los Angles: north 33º 56.4', west 118º 24.0' = 33.94º, -118.40º"
Line 2,162 ⟶ 2,553:
asin: Return RxCalcArcSin(arg(1),,'R')
sqrt: Return RxCalcSqrt(arg(1))
::requires rxMath library</langsyntaxhighlight>
{{out}}
<pre> Nashville: north 36º 7.2', west 86º 40.2' = 36.12º, -86.67º
Line 2,172 ⟶ 2,563:
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">dist(th1, th2, ph)={
my(v=[cos(ph)*cos(th1)-cos(th2),sin(ph)*cos(th1),sin(th1)-sin(th2)]);
asin(sqrt(norml2(v))/2)
Line 2,180 ⟶ 2,571:
d*dist(th1*deg, th2*deg, (ph1-ph2)*deg)
};
distEarth(36.12, -86.67, 33.94, -118.4)</langsyntaxhighlight>
{{out}}
<pre>%1 = 2886.44444</pre>
Line 2,186 ⟶ 2,577:
=={{header|Pascal}}==
{{works with|Free_Pascal}} {{libheader|Math}}
<langsyntaxhighlight lang="pascal">Program HaversineDemo(output);
 
uses
Line 2,209 ⟶ 2,600:
begin
writeln ('Haversine distance: ', haversineDist(36.12, -86.67, 33.94, -118.4):7:2, ' km.');
end.</langsyntaxhighlight>
{{out}}
<pre>Haversine distance: 2887.26 km.
Line 2,215 ⟶ 2,606:
 
=={{header|Perl}}==
 
===Low-Level===
 
{{libheader|ntheory}}
<langsyntaxhighlight lang="perl">use ntheory qw/Pi/;
 
sub asin { my $x = shift; atan2($x, sqrt(1-$x*$x)); }
Line 2,234 ⟶ 2,628:
my @BNA = (36.12, -86.67);
my @LAX = (33.94, -118.4);
printf "Distance: %.3f km\n", surfacedist(@BNA, @LAX);</langsyntaxhighlight>
{{out}}
<pre>Distance: 2887.260 km</pre>
 
===Idiomatic===
 
Contrary to ntheory, Math::Trig is part of the Perl core distribution.
It comes with a great circle distance built-in.
 
<syntaxhighlight lang="perl">use Math::Trig qw(great_circle_distance deg2rad);
# Notice the 90 - latitude: phi zero is at the North Pole.
# Parameter order is: LON, LAT
my @BNA = (deg2rad(-86.67), deg2rad(90 - 36.12));
my @LAX = (deg2rad(-118.4), deg2rad(90 - 33.94));
 
print "Distance: ", great_circle_distance(@BNA, @LAX, 6372.8), " km\n";</syntaxhighlight>
{{out}}
<pre>Distance: 2887.25995060711 km</pre>
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">function</span> <span style="color: #000000;">haversine</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">lat1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">long1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">lat2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">long2</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">MER</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">6371</span><span style="color: #0000FF;">,</span> <span style="color: #000080;font-style:italic;">-- mean earth radius(km)</span>
Line 2,252 ⟶ 2,662:
<span style="color: #004080;">atom</span> <span style="color: #000000;">d</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">haversine</span><span style="color: #0000FF;">(</span><span style="color: #000000;">36.12</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">86.67</span><span style="color: #0000FF;">,</span><span style="color: #000000;">33.94</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">118.4</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Distance is %f km (%f miles)\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">d</span><span style="color: #0000FF;">,</span><span style="color: #000000;">d</span><span style="color: #0000FF;">/</span><span style="color: #000000;">1.609344</span><span style="color: #0000FF;">})</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 2,259 ⟶ 2,669:
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php">class POI {
private $latitude;
private $longitude;
Line 2,292 ⟶ 2,702:
return $distance;
}
}</langsyntaxhighlight>
'''Test:'''
<langsyntaxhighlight lang="php">$bna = new POI(36.12, -86.67); // Nashville International Airport
$lax = new POI(33.94, -118.40); // Los Angeles International Airport
printf('%.2f km', $bna->getDistanceInMetersTo($lax));</langsyntaxhighlight>
{{out}}
<pre>2886.44 km</pre>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(scl 12)
(load "@lib/math.l")
 
Line 2,317 ⟶ 2,727:
(/
(sqrt (+ (* DX DX) (* DY DY) (* DZ DZ)))
2 ) ) ) ) )</langsyntaxhighlight>
Test:
<langsyntaxhighlight PicoLisplang="picolisp">(prinl
"Haversine distance: "
(round (haversine 36.12 -86.67 33.94 -118.4))
" km" )</langsyntaxhighlight>
{{out}}
<pre>Haversine distance: 2,886.444 km</pre>
 
=={{header|PL/I}}==
<langsyntaxhighlight PLlang="pl/Ii">test: procedure options (main); /* 12 January 2014. Derived from Fortran version */
declare d float;
 
Line 2,355 ⟶ 2,765:
end haversine;
 
end test;</langsyntaxhighlight>
{{out}}
<pre>
Line 2,363 ⟶ 2,773:
=={{header|PowerShell}}==
{{works with|PowerShell|3}}
<syntaxhighlight lang="powershell">
<lang PowerShell>
Add-Type -AssemblyName System.Device
Line 2,370 ⟶ 2,780:
$BNA.GetDistanceTo( $LAX ) / 1000
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,376 ⟶ 2,786:
</pre>
{{works with|PowerShell|2}}
<syntaxhighlight lang="powershell">
<lang PowerShell>
function Get-GreatCircleDistance ( $Coord1, $Coord2 )
{
Line 2,405 ⟶ 2,815:
Get-GreatCircleDistance $BNA $LAX
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,487 ⟶ 2,897:
=={{header|PureBasic}}==
{{trans|Pascal}}
<langsyntaxhighlight PureBasiclang="purebasic">#DIA=2*6372.8
 
Procedure.d Haversine(th1.d,ph1.d,th2.d,ph2.d)
Line 2,507 ⟶ 2,917:
Print("Haversine distance: ")
Print(StrD(Haversine(36.12,-86.67,33.94,-118.4),7)+" km.")
Input()</langsyntaxhighlight>
{{out}}
<pre>Haversine distance: 2887.2599506 km.</pre>
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">from math import radians, sin, cos, sqrt, asin
 
 
Line 2,530 ⟶ 2,940:
>>> haversine(36.12, -86.67, 33.94, -118.40)
2887.2599506071106
>>> </langsyntaxhighlight>
 
=={{header|QB64}}==
{{trans|BASIC}}
<syntaxhighlight lang="qb64">
<lang QB64>
SCREEN _NEWIMAGE(800, 100, 32)
 
Line 2,587 ⟶ 2,997:
 
END
</syntaxhighlight>
</lang>
 
=={{header|R}}==
<langsyntaxhighlight lang="r">dms_to_rad <- function(d, m, s) (d + m / 60 + s / 3600) * pi / 180
 
# Volumetric mean radius is 6371 km, see http://nssdc.gsfc.nasa.gov/planetary/factsheet/earthfact.html
Line 2,609 ⟶ 3,019:
dms_to_rad(33, 56, 32.98), dms_to_rad(118, 24, 29.05)) # Los Angeles International Airport (LAX)
 
# Output: 2886.327</langsyntaxhighlight>
 
=={{header|Racket}}==
Almost the same as the Scheme version.
<langsyntaxhighlight lang="racket">
#lang racket
(require math)
Line 2,629 ⟶ 3,039:
(distance (deg-to-rad 36 7.2 0) (deg-to-rad 86 40.2 0)
(deg-to-rad 33 56.4 0) (deg-to-rad 118 24.0 0))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,637 ⟶ 3,047:
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" perl6line>class EarthPoint {
has $.lat; # latitude
has $.lon; # longitude
Line 2,665 ⟶ 3,075:
my EarthPoint $LAX .= new(lat => 33.94, lon => -118.4);
 
say $BNA.haversine-dist($LAX); # 2886.44444099822</langsyntaxhighlight>
 
=={{header|Raven}}==
{{trans|Groovy}}
<langsyntaxhighlight Ravenlang="raven">define PI
-1 acos
 
Line 2,693 ⟶ 3,103:
}
-118.40 33.94 -86.67 36.12 haversine "haversine: %.15g\n" print</langsyntaxhighlight>
{{out}}
<pre>haversine: 2887.25995060711</pre>
Line 2,700 ⟶ 3,110:
The use of normalization for angles isn't required for the Haversine formula, but those normalization functions were included
<br>herein anyway &nbsp; (to support normalization of input arguments to the trigonometric functions for the general case).
<langsyntaxhighlight lang="rexx">/*REXX program calculates the distance between Nashville and Los Angles airports.*/
call pi; numeric digits length(pi) % 2 /*use half of PI dec. digits for output*/
say " Nashville: north 36º 7.2', west 86º 40.2' = 36.12º, -86.67º"
Line 2,752 ⟶ 3,162:
numeric digits; parse value format(x,2,1,,0) 'E0' with g "E" _ .; g=g * .5'e'_ % 2
do j=0 while h>9; m.j= h; h= h%2 + 1; end /*j*/
do k=j+5 to 0 by -1; numeric digits m.k; g= (g+x/g)*.5; end /*k*/; return g</langsyntaxhighlight>
REXX doesn't have most of the higher math functions, so they are included here (above) as subroutines (functions).
╔════════════════════════════════════════════════════════════════════════╗
Line 2,789 ⟶ 3,199:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
decimals(8)
see haversine(36.12, -86.67, 33.94, -118.4) + nl
Line 2,805 ⟶ 3,215:
d = 6372.8 * c
return d
</syntaxhighlight>
</lang>
 
=={{header|RPL}}==
{{works with|Halcyon Calc|4.2.7}}
{| class="wikitable"
! Code
! Comments
|-
|
ROT - 2 / DEG SIN SQ OVER COS * 3 PICK COS *
ROT ROT - 2 / SIN SQ + √ RAD ASIN 6372.8 * 2 *
≫ 'AHAV' STO
|
''( lat1 lon1 lat2 lon2 -- distance )''
Start by the end of the formula, in degree mode
Switch to radian mode to compute Arcsin
|}
The following line of command delivers what is required:
36.12 -86.67 33.94 -118.4 AHAV
Due to the uncertainty in values of Earth radius and airports coordinates, the result shall be announced as 2887 ± 1 km even if the calculation provides many digits after the decimal point
{{out}}
<pre>
1: 2887.25995061
</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">include Math
 
Radius = 63716372.8 # rough radius of the Earth, in kilometers
 
def spherical_distance(start_coords, end_coords)
Line 2,825 ⟶ 3,260:
lax = [33.94, -118.4]
 
puts "%.1f" % spherical_distance(bna, lax)</langsyntaxhighlight>
 
{{out}}
<pre>28862887.43</pre>
 
Alternatively:
Alternativley:
 
{{trans|Python}}
<langsyntaxhighlight lang="ruby">include Math
def haversine(lat1, lon1, lat2, lon2)
Line 2,850 ⟶ 3,285:
 
puts "distance is #{haversine(36.12, -86.67, 33.94, -118.40)} km "
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,857 ⟶ 3,292:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic"> D2R = atn(1)/45
diam = 2 * 6372.8
Lg1m2 = ((-86.67)-(-118.4)) * D2R
Line 2,876 ⟶ 3,311:
' Directions (destination).
' 36.12.-86.66999
' Distance is 35.37 inches.</langsyntaxhighlight>Output <pre>Haversine distance: 2887.2599506071104 km.</pre>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">
use std::f64;
 
static R: f64 = 6372.8;
 
struct Point {
lat: f64,
Line 2,889 ⟶ 3,320:
}
 
fn haversine(mut origin: Point, mut destination: Point) -> f64 {
origin.lonconst R: f64 -= destination6372.lon8;
origin.lon = origin.lon.to_radians();
origin.lat = origin.lat.to_radians();
destination.lat = destination.lat.to_radians();
let dz: f64 = origin.lat.sin() - destination.lat.sin();
let dx: f64 = origin.lon.cos() * origin.lat.cos() - destination.lat.cos();
let dy: f64 = origin.lon.sin() * origin.lat.cos();
((dx * dx + dy * dy + dz * dz).sqrt() / 2.0).asin() * 2.0 * R
}
 
let lat1 = origin.lat.to_radians();
fn main() {
let origin: Pointlat2 = Point {destination.lat.to_radians();
let d_lat = lat2 lat:- 36.12,lat1;
let d_lon = (destination.lon - origin.lon).to_radians();
lon:-86.67
 
};
let a = (d_lat / 2.0).sin().powi(2) + (d_lon / 2.0).sin().powi(2) * lat1.cos() * lat2.cos();
let destination: Point = Point {
let c = 2.0 lat:* 33a.sqrt().94,asin();
R * lon:-118.4c
};
let d: f64 = haversine(origin, destination);
println!("Distance: {} km ({} mi)", d, d / 1.609344);
}
 
#[cfg(test)]
</lang>Output <pre>Distance: 2887.2599506071106 km (1794.060157807846 mi)</pre>
mod test {
use super::{Point, haversine};
 
#[test]
fn test_haversine() {
let origin: Point = Point {
lat: 36.12,
lon: -86.67
};
let destination: Point = Point {
lat: 33.94,
lon: -118.4
};
let d: f64 = haversine(origin, destination);
println!("Distance: {} km ({} mi)", d, d / 1.609344);
assert_eq!(d, 2887.2599506071106);
}
 
}
</syntaxhighlight>Output <pre>Distance: 2887.2599506071106 km (1794.060157807846 mi)</pre>
 
=={{header|SAS}}==
<syntaxhighlight lang="sas">
<lang SAS>
options minoperator;
 
Line 2,968 ⟶ 3,408:
 
%haver(36.12, -86.67, 33.94, -118.40);
</syntaxhighlight>
</lang>
{{out}}
<pre>Distance is 2887.2599506 K</pre>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">import math._
 
object Haversine {
Line 2,990 ⟶ 3,430:
println(haversine(36.12, -86.67, 33.94, -118.40))
}
}</langsyntaxhighlight>
{{out}}
<pre>2887.2599506071106</pre>
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">(define earth-radius 6371)
(define pi (acos -1))
 
Line 3,006 ⟶ 3,446:
(distance (deg-to-rad 36 7.2 0) (deg-to-rad 86 40.2 0)
(deg-to-rad 33 56.4 0) (deg-to-rad 118 24.0 0))
; 2886.444442837984</langsyntaxhighlight>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "float.s7i";
include "math.s7i";
Line 3,034 ⟶ 3,474:
degToRad(33.94), degToRad(-118.4)) # Los Angeles International Airport (LAX)
digits 2);
end func;</langsyntaxhighlight>
 
{{out}}
Line 3,043 ⟶ 3,483:
=={{header|Sidef}}==
{{trans|Raku}}
<langsyntaxhighlight lang="ruby">class EarthPoint(lat, lon) {
 
const earth_radius = 6371 # mean earth radius
Line 3,071 ⟶ 3,511:
var LAX = EarthPoint.new(lat: 33.94, lon: -118.4)
 
say BNA.haversine_dist(LAX) #=> 2886.444442837983299747157823945746716...</langsyntaxhighlight>
 
=={{header|smart BASIC}}==
{{trans|BASIC}}
<langsyntaxhighlight lang="smart BASICbasic">
'*** LAT/LONG for Nashville International Airport (BNA)
lat1=36.12
Line 3,117 ⟶ 3,557:
 
ENDDEF
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,128 ⟶ 3,568:
First, a program to add a distance variable to a dataset, given variables for LAT/LON of two points.
 
<langsyntaxhighlight lang="stata">program spheredist
version 15.0
syntax varlist(min=4 max=4 numeric), GENerate(namelist max=1) ///
Line 3,144 ⟶ 3,584:
label variable `generate' `"`label'"'
}
end</langsyntaxhighlight>
 
Illustration with a sample dataset.
 
<langsyntaxhighlight lang="stata">import delimited airports.csv, clear
format %9.4f l*
list
Line 3,162 ⟶ 3,602:
|----------------------------------------------------------------------------------------------------|
6. | MEM Memphis International Airport Memphis United States 35.0424 -89.9767 |
+----------------------------------------------------------------------------------------------------+</langsyntaxhighlight>
 
MEM/CGN joins two Fedex Express hubs. The line AMS/LAX is operated by KLM Royal Dutch Airlines.
Line 3,169 ⟶ 3,609:
Bear in mind that the actual route of an airliner is usually not a piece of great circle, so this will only give an idea. For instance, according to [http://flightaware.com/ FlightAware], the route of a Fedex flight from Memphis to Paris is 7852 km long, at FL300 altitude (9150 m). The program given here would yield 7328.33 km instead.
 
<langsyntaxhighlight lang="stata">keep iata lat lon
rename (iata lat lon) =2
gen k=0
Line 3,200 ⟶ 3,640:
14. | CGN 50.8659 7.1427 MEM 35.0424 -89.9767 |
15. | LAX 33.9425 -118.4080 MEM 35.0424 -89.9767 |
+-----------------------------------------------------------+</langsyntaxhighlight>
 
Now compute the distances and print the result.
 
<langsyntaxhighlight lang="stata">spheredist lat1 lon1 lat2 lon2, gen(dist) lab(Distance at sea level)
spheredist lat1 lon1 lat2 lon2, gen(fl350) alt(10680) lab(Distance at FL350 altitude)
format %9.2f dist fl350
Line 3,229 ⟶ 3,669:
14. | CGN MEM 7514.96 7527.70 |
15. | LAX MEM 2599.71 2604.12 |
+-----------------------------------+</langsyntaxhighlight>
 
Notice that the distance from Nashville to Los Angeles is given as 2886.32 km, which is slightly different from the task description. The coordinates come from [https://openflights.org/html/apsearch OpenFlights] and are supposably more accurate. Using the data in the task description, one gets 2886.44 as expected.
Line 3,235 ⟶ 3,675:
=={{header|Swift}}==
{{trans|Objective-C}}
<langsyntaxhighlight Swiftlang="swift">import Foundation
 
func haversine(lat1:Double, lon1:Double, lat2:Double, lon2:Double) -> Double {
Line 3,252 ⟶ 3,692:
}
 
print(haversine(lat1:36.12, lon1:-86.67, lat2:33.94, lon2:-118.40))</langsyntaxhighlight>
{{out}}
<pre>
Line 3,260 ⟶ 3,700:
=={{header|Symsyn}}==
 
<syntaxhighlight lang="symsyn">
<lang Symsyn>
lat1 : 36.12
lon1 : -86.67
Line 3,282 ⟶ 3,722:
 
"'Haversine distance: ' kms ' kms'" []
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,289 ⟶ 3,729:
 
=={{header|tbas}}==
<langsyntaxhighlight lang="qbasic">
option angle radians ' the default
sub haversine(lat1, lon1, lat2, lon2)
Line 3,307 ⟶ 3,747:
print using "Nashville International Airport to Los Angeles International Airport ####.########### km", haversine(36.12, -86.67, 33.94, -118.40)
print using "Perth, WA Australia to Baja California, Mexico #####.########### km", haversine(-31.95, 115.86, 31.95, -115.86)
</syntaxhighlight>
</lang>
<pre>
Nashville International Airport to Los Angeles International Airport 2887.25995060712 km
Line 3,316 ⟶ 3,756:
=={{header|Tcl}}==
{{trans|Groovy}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
proc haversineFormula {lat1 lon1 lat2 lon2} {
set rads [expr atan2(0,-1)/180]
Line 3,332 ⟶ 3,772:
 
# Don't bother with too much inappropriate accuracy!
puts [format "distance=%.1f km" [haversineFormula 36.12 -86.67 33.94 -118.40]]</langsyntaxhighlight>
{{out}}
<pre>distance=2887.3 km</pre>
 
=={{header|TechBASIC}}==
<syntaxhighlight lang="techbasic">
<lang TechBASIC>
{{trans|BASIC}}
FUNCTION HAVERSINE
Line 3,369 ⟶ 3,809:
 
END FUNCTION
</syntaxhighlight>
</lang>
 
 
Line 3,413 ⟶ 3,853:
 
=={{header|Teradata Stored Procedure}}==
<syntaxhighlight lang="sql">
<lang SQL>
# syntax: call SP_HAVERSINE(36.12,33.94,-86.67,-118.40,x);
 
Line 3,440 ⟶ 3,880:
select km into distance;
END;
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,448 ⟶ 3,888:
=={{header|Transact-SQL}}==
{{trans|C#}}
<langsyntaxhighlight SQLlang="sql">CREATE FUNCTION [dbo].[Haversine](@Lat1 AS DECIMAL(9,7), @Lon1 AS DECIMAL(10,7), @Lat2 AS DECIMAL(9,7), @Lon2 AS DECIMAL(10,7))
RETURNS DECIMAL(12,7)
AS
Line 3,471 ⟶ 3,911:
 
SELECT dbo.Haversine(36.12,-86.67,33.94,-118.4)
</syntaxhighlight>
</lang>
{{out}}
<pre>
2887.2594934
</pre>
 
 
=={{header|True BASIC}}==
<lang basic>
DEF Haversine (lat1, long1, lat2, long2)
OPTION ANGLE RADIANS
LET R = 6372.8 !radio terrestre en km.
LET dLat = RAD(lat2-lat1)
LET dLong = RAD(long2-long1)
LET lat1 = RAD(lat1)
LET lat2 = RAD(lat2)
LET Haversine = R *2 * ASIN(SQR(SIN(dLat/2)^2 + SIN(dLong/2)^2 *COS(lat1) * COS(lat2)))
END DEF
PRINT
 
PRINT "Distancia de Haversine:"; Haversine(36.12, -86.67, 33.94, -118.4); "km"
END
</lang>
{{out}}
<pre>
Distancia de Haversine: 2887.26 km
</pre>
 
 
=={{header|TypeScript}}==
{{trans|Matlab}}
<langsyntaxhighlight lang="javascript">
let radians = function (degree: number) {
 
Line 3,527 ⟶ 3,944:
 
console.log("Distance:" + haversine(36.12, -86.67, 33.94, -118.40));
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,535 ⟶ 3,952:
 
=={{header|UBASIC}}==
<langsyntaxhighlight lang="basic">
10 Point 7 'Sets decimal display to 32 places (0+.1^56)
20 Rf=#pi/180 'Degree -> Radian Conversion
Line 3,549 ⟶ 3,966:
2887.2599506 km
OK
</syntaxhighlight>
</lang>
 
=={{header|VBA}}==
{{trans|Phix}}<langsyntaxhighlight lang="vb">Const MER = 6371 '-- mean earth radius(km)
Public DEG_TO_RAD As Double
Line 3,567 ⟶ 3,984:
d = haversine(36.12, -86.67, 33.94, -118.4)
Debug.Print "Distance is "; Format(d, "#.######"); " km ("; Format(d / 1.609344, "#.######"); " miles)."
End Sub</langsyntaxhighlight>{{out}}
<pre>Distance is 2886,444443 km (1793,553425 miles).</pre>
 
=={{header|Visual Basic .NET}}==
{{trans|C#}}If you read the fine print in the Wikipedia article, you will find that the Haversine method of finding distances may have an error of up to 0.5%. This could lead one to believe that discussion about whether to use 6371.0 km or 6372.8 km for an approximation of the Earth's radius is moot.
<langsyntaxhighlight lang="vbnet">Imports System.Math
 
Module Module1
Line 3,623 ⟶ 4,040:
ShowOne(New AP_Loc("LNZ", 48.233, 14.183), New AP_Loc("N/A", 48.233, 14.188))
End Sub
End Module</langsyntaxhighlight>
{{out}}
<pre>The approximate distance between airports BNA: (36.124, -86.678) and LAX: (33.942, -118.408) is 2,886.36 km.
Line 3,633 ⟶ 4,050:
The approximate distance between airports LNZ: (48.233, 14.183) and N/A: (48.233, 14.188) is 370.34 m.
The uncertainty is under 0.5%, or 1.9 m.</pre>Looking at the altitude difference between the last two airports, (299 - 96 = 203), the reported distance of 370 meters ought to be around 422 meters if you actually went there and saw it for yourself.
 
=={{header|V (Vlang)}}==
{{trans|go}}
<syntaxhighlight lang="v (vlang)">import math
 
fn haversine(h f64) f64 {
return .5 * (1 - math.cos(h))
}
struct Pos {
lat f64 // latitude, radians
long f64 // longitude, radians
}
fn deg_pos(lat f64, lon f64) Pos {
return Pos{lat * math.pi / 180, lon * math.pi / 180}
}
const r_earth = 6372.8 // km
fn hs_dist(p1 Pos, p2 Pos) f64 {
return 2 * r_earth * math.asin(math.sqrt(haversine(p2.lat-p1.lat)+
math.cos(p1.lat)*math.cos(p2.lat)*haversine(p2.long-p1.long)))
}
fn main() {
println(hs_dist(deg_pos(36.12, -86.67), deg_pos(33.94, -118.40)))
}</syntaxhighlight>
{{out}}
<pre>2887.2599506071</pre>
 
=={{header|Wren}}==
{{trans|Julia}}
<langsyntaxhighlight ecmascriptlang="wren">var R = 6372.8 // Earth's approximate radius in kilometers.
 
/* Class containing trig methods which work with degrees rather than radians. */
Line 3,651 ⟶ 4,098:
}
 
System.print(haversine.call(36.12, -86.67, 33.94, -118.4))</langsyntaxhighlight>
 
{{out}}
Line 3,660 ⟶ 4,107:
=={{header|X86 Assembly}}==
Assemble with tasm /m /l; tlink /t
<langsyntaxhighlight lang="asm">0000 .model tiny
0000 .code
.486
Line 3,745 ⟶ 4,192:
;(TASM isn't smart enough to do floating point constant calculations)
end start
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,752 ⟶ 4,199:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
 
func real Haversine(Ang);
Line 3,765 ⟶ 4,212:
 
def D2R = 3.141592654/180.0; \degrees to radians
RlOut(0, Dist(36.12*D2R, 33.94*D2R, -86.67*D2R, -118.40*D2R ));</langsyntaxhighlight>
 
{{out}}
Line 3,773 ⟶ 4,220:
 
=={{header|XQuery}}==
<langsyntaxhighlight XQuerylang="xquery">declare namespace xsd = "http://www.w3.org/2001/XMLSchema";
declare namespace math = "http://www.w3.org/2005/xpath-functions/math";
 
Line 3,788 ⟶ 4,235:
};
 
local:haversine(36.12, -86.67, 33.94, -118.4)</langsyntaxhighlight>
 
{{out}}
Line 3,795 ⟶ 4,242:
</pre>
 
=={{header|Zig}}==
{{trans|R}}
 
When a Zig <em>struct</em> type can be inferred then anonymous structs .{} can be used for initialisation.
=={{header|Yabasic}}==
This can be seen on the lines where the constants <em>bna</em> and <em>lax</em> are instantiated.
{{trans|FreeBASIC}}
<lang Yabasic>
//pi está predefinido en Yabasic
deg2rad = pi / 180 // define grados a radianes 0.01745..
radioTierra = 6372.8 // radio de la tierra en km
 
A Zig <em>struct</em> can have methods, the same as an <em>enum</em> and or a <em>union</em>.
sub Haversine(lat1, long1, lat2, long2 , radio)
They are only namespaced functions that can be called with dot syntax.
d_long = deg2rad * (long1 - long2)
theta1 = deg2rad * lat1
theta2 = deg2rad * lat2
dx = cos(d_long) * cos(theta1) - cos(theta2)
dy = sin(d_long) * cos(theta1)
dz = sin(theta1) - sin(theta2)
return asin(sqr(dx*dx + dy*dy + dz*dz) / 2) * radio * 2
end sub
 
<syntaxhighlight lang="zig">
print " Distancia de Haversine entre BNA y LAX = ", Haversine(36.12, -86.67, 33.94, -118.4, radioTierra), " km"
const std = @import("std");
end
const math = std.math; // Save some typing, reduce clutter. Otherwise math.sin() would be std.math.sin() etc.
</lang>
{{out}}
<pre>
Distancia de Haversine entre BNA y LAX = 259.478 km
</pre>
 
pub fn main() !void {
// Coordinates are found here:
// http://www.airport-data.com/airport/BNA/
// http://www.airport-data.com/airport/LAX/
 
const bna = LatLong{
.lat = .{ .d = 36, .m = 7, .s = 28.10 },
.long = .{ .d = 86, .m = 40, .s = 41.50 },
};
 
const lax = LatLong{
.lat = .{ .d = 33, .m = 56, .s = 32.98 },
.long = .{ .d = 118, .m = 24, .s = 29.05 },
};
 
const distance = calcGreatCircleDistance(bna, lax);
 
std.debug.print("Output: {d:.6} km\n", .{distance});
 
// Output: 2886.326609 km
}
 
const LatLong = struct { lat: DMS, long: DMS };
 
/// degrees, minutes, decimal seconds
const DMS = struct {
d: f64,
m: f64,
s: f64,
 
fn toRadians(self: DMS) f64 {
return (self.d + self.m / 60 + self.s / 3600) * math.pi / 180;
}
};
 
// Volumetric mean radius is 6371 km, see http://nssdc.gsfc.nasa.gov/planetary/factsheet/earthfact.html
// The diameter is thus 12742 km
fn calcGreatCircleDistance(lat_long1: LatLong, lat_long2: LatLong) f64 {
const lat1 = lat_long1.lat.toRadians();
const lat2 = lat_long2.lat.toRadians();
const long1 = lat_long1.long.toRadians();
const long2 = lat_long2.long.toRadians();
 
const a = math.sin(0.5 * (lat2 - lat1));
const b = math.sin(0.5 * (long2 - long1));
 
return 12742 * math.asin(math.sqrt(a * a + math.cos(lat1) * math.cos(lat2) * b * b));
}
</syntaxhighlight>
 
=={{header|zkl}}==
{{trans|Erlang}}
<langsyntaxhighlight lang="zkl">haversine(36.12, -86.67, 33.94, -118.40).println();
fcn haversine(Lat1, Long1, Lat2, Long2){
Line 3,837 ⟶ 4,320:
C := 2.0 * A.sqrt().asin();
R*C;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,845 ⟶ 4,328:
=={{header|ZX Spectrum Basic}}==
{{trans|Run_BASIC}}
<langsyntaxhighlight lang="zxbasic">10 LET diam=2*6372.8
20 LET Lg1m2=FN r((-86.67)-(-118.4))
30 LET Lt1=FN r(36.12)
Line 3,855 ⟶ 4,338:
90 PRINT "Haversine distance: ";hDist;" km."
100 STOP
1000 DEF FN r(a)=a*0.017453293: REM convert degree to radians</langsyntaxhighlight>
 
[[Category:Geometry]]
9,476

edits