Skip to content

Instantly share code, notes, and snippets.

@carrotflakes
Last active October 8, 2023 07:53
Show Gist options
  • Save carrotflakes/dc98789a2f21cd813d4fbf0b2f1cb2bf to your computer and use it in GitHub Desktop.
Save carrotflakes/dc98789a2f21cd813d4fbf0b2f1cb2bf to your computer and use it in GitHub Desktop.
great-circular distance and its derivative
fn distance_on_sphere(lat1: f32, lon1: f32, lat2: f32, lon2: f32) -> f32 {
let dlat = (lat2 - lat1).abs();
let dlon = (lon2 - lon1).abs();
let a = (dlat * 0.5).sin().powi(2) + lat1.cos() * lat2.cos() * (dlon * 0.5).sin().powi(2);
2.0 * a.sqrt().asin()
}
fn differential_distance_on_sphere(lat1: f32, lon1: f32, lat2: f32, lon2: f32) -> [f32; 2] {
let diff = 1.0;
let dlat = (lat2 - lat1).abs();
let dlon = (lon2 - lon1).abs();
let dlatsign = (lat2 - lat1).signum();
let dlonsign = (lon2 - lon1).signum();
let cc = lat1.cos() * lat2.cos();
let (dlatsin, dlatcos) = (dlat * 0.5).sin_cos();
let (dlonsin, dloncos) = (dlon * 0.5).sin_cos();
let a = dlatsin.powi(2) + cc * dlonsin.powi(2);
let e = diff / ((1.0 - a.abs()).sqrt() * a.sqrt()).max(1e-8);
let dlon1 = -(dlonsign * dlonsin * dloncos * cc * e);
let d = dlatcos * dlatsin * e;
let dlat1 = -lat1.sin() * lat2.cos() * e * dlonsin.powi(2) - dlatsign * d;
[dlat1, dlon1]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment