calc_distance_on_unit_sphere¶
- pyhelpers.geom.calc_distance_on_unit_sphere(pt1, pt2, unit='mile', precision=None)[source]¶
Calculate the distance between two points on a unit sphere.
This function computes the spherical distance between two points
pt1
andpt2
. The distance can be returned in either miles ('mile'
) or kilometers ('km'
) based on theunit
parameter.- Parameters:
pt1 (shapely.geometry.Point | tuple | numpy.ndarray) – One point.
pt2 (shapely.geometry.Point | tuple | numpy.ndarray) – Another point.
unit (str) – Unit of distance for output; options include
'mile'
(default) and'km'
.precision (int | None) – Number of decimal places for the calculated result; defaults to
None
(no rounding).
- Returns:
Distance between
pt1
andpt2
in miles or kilometers (relative to the earth’s radius).- Return type:
float | None
Examples:
>>> from pyhelpers.geom import calc_distance_on_unit_sphere >>> from pyhelpers._cache import example_dataframe >>> example_df = example_dataframe() >>> example_df Longitude Latitude City London -0.127647 51.507322 Birmingham -1.902691 52.479699 Manchester -2.245115 53.479489 Leeds -1.543794 53.797418 >>> london, birmingham = example_df.loc[['London', 'Birmingham']].values >>> london array([-0.1276474, 51.5073219]) >>> birmingham array([-1.9026911, 52.4796992]) >>> arc_len_in_miles = calc_distance_on_unit_sphere(london, birmingham) >>> arc_len_in_miles # in miles 101.10431101941569 >>> arc_len_in_miles = calc_distance_on_unit_sphere(london, birmingham, precision=4) >>> arc_len_in_miles 101.1043
Note
This function is modified from the original code available at [GEOM-CDOUS-1]. It assumes the earth is perfectly spherical and returns the distance based on each point’s longitude and latitude.