Skip to content

Commit 86a85b6

Browse files
authored
Add formulas used in navigation (TheAlgorithms#464)
1 parent 1774322 commit 86a85b6

File tree

4 files changed

+81
-0
lines changed

4 files changed

+81
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ pub mod dynamic_programming;
99
pub mod general;
1010
pub mod graph;
1111
pub mod math;
12+
pub mod navigation;
1213
pub mod searching;
1314
pub mod sorting;
1415
pub mod string;

src/navigation/bearing.rs

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
use std::f64::consts::PI;
2+
3+
pub fn bearing(lat1: f64, lng1: f64, lat2: f64, lng2: f64) -> f64 {
4+
let lat1 = lat1 * PI / 180.0;
5+
let lng1 = lng1 * PI / 180.0;
6+
7+
let lat2 = lat2 * PI / 180.0;
8+
let lng2 = lng2 * PI / 180.0;
9+
10+
let delta_longitude = lng2 - lng1;
11+
12+
let y = delta_longitude.sin() * lat2.cos();
13+
let x = lat1.cos() * lat2.sin() - lat1.sin() * lat2.cos() * delta_longitude.cos();
14+
15+
let mut brng = y.atan2(x);
16+
brng = brng.to_degrees();
17+
18+
(brng + 360.0) % 360.0
19+
}
20+
21+
#[cfg(test)]
22+
mod tests {
23+
use super::*;
24+
25+
#[test]
26+
fn testing() {
27+
assert_eq!(
28+
format!(
29+
"{:.0}º",
30+
bearing(
31+
-27.2020447088982,
32+
-49.631891179172555,
33+
-3.106362,
34+
-60.025826,
35+
)
36+
),
37+
"336º"
38+
);
39+
}
40+
}

src/navigation/haversine.rs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
use std::f64::consts::PI;
2+
3+
const EARTH_RADIUS: f64 = 6371000.00;
4+
5+
pub fn haversine(lat1: f64, lng1: f64, lat2: f64, lng2: f64) -> f64 {
6+
let delta_dist_lat = (lat2 - lat1) * PI / 180.0;
7+
let delta_dist_lng = (lng2 - lng1) * PI / 180.0;
8+
9+
let cos1 = lat1 * PI / 180.0;
10+
let cos2 = lat2 * PI / 180.0;
11+
12+
let delta_lat = (delta_dist_lat / 2.0).sin().powf(2.0);
13+
let delta_lng = (delta_dist_lng / 2.0).sin().powf(2.0);
14+
15+
let a = delta_lat + delta_lng * cos1.cos() * cos2.cos();
16+
let result = 2.0 * a.asin().sqrt();
17+
18+
result * EARTH_RADIUS
19+
}
20+
21+
#[cfg(test)]
22+
mod tests {
23+
use super::*;
24+
25+
#[test]
26+
fn testing() {
27+
assert_eq!(
28+
format!(
29+
"{:.2}km",
30+
haversine(52.375603, 4.903206, 52.366059, 4.926692) / 1000.0
31+
),
32+
"1.92km"
33+
);
34+
}
35+
}

src/navigation/mod.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
mod bearing;
2+
mod haversine;
3+
4+
pub use self::bearing::bearing;
5+
pub use self::haversine::haversine;

0 commit comments

Comments
 (0)