use std::f64::consts::PI;
// ------------------------------------------------------------
// Convert degrees to radians
// ------------------------------------------------------------
fn deg_to_rad(deg: f64) -> f64 {
deg * PI / 180.0
}
// ------------------------------------------------------------
// Compute the great-circle distance between two points on Earth
// using the Haversine formula.
// lat1, lon1, lat2, lon2 are in degrees.
// The result is returned in kilometers.
// ------------------------------------------------------------
fn haversine(lat1: f64, lon1: f64, lat2: f64, lon2: f64) -> f64 {
// Earth's mean radius in kilometers
const R: f64 = 6371.0;
// Convert all angles to radians
let rlat1 = deg_to_rad(lat1);
let rlon1 = deg_to_rad(lon1);
let rlat2 = deg_to_rad(lat2);
let rlon2 = deg_to_rad(lon2);
// Differences
let dlat = rlat2 - rlat1;
let dlon = rlon2 - rlon1;
// Haversine formula
// a is the Haversine of the central angle between the two points.
let a =
(f64::sin(dlat / 2.0)).powi(2) +
f64::cos(rlat1) * f64::cos(rlat2) *
(f64::sin(dlon / 2.0)).powi(2);
// Central angle
// c is the central angle between the two points on the Earth’s surface.
let c = 2.0 * f64::asin(f64::sqrt(a));
// Final distance
R * c
}
fn main() {
// Example coordinates:
// Austin, Texas
let lat1: f64 = 30.2672;
let lon1: f64 = -97.7431;
// Houston, Texas
let lat2: f64 = 29.7604;
let lon2: f64 = -95.3698;
let distance_km: f64 = haversine(lat1, lon1, lat2, lon2);
// Convert kilometers to miles
let distance_miles: f64 = distance_km * 0.621371;
println!("Distance: {:.3} km", distance_km);
println!("Distance: {:.3} miles", distance_miles);
}
/*
run:
Distance: 235.352 km
Distance: 146.241 miles
*/