1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
use crate::{CoordFloat, Point, MEAN_EARTH_RADIUS};
use num_traits::FromPrimitive;
pub trait HaversineDistance<T, Rhs = Self> {
fn haversine_distance(&self, rhs: &Rhs) -> T;
}
impl<T> HaversineDistance<T, Point<T>> for Point<T>
where
T: CoordFloat + FromPrimitive,
{
fn haversine_distance(&self, rhs: &Point<T>) -> T {
let two = T::one() + T::one();
let theta1 = self.y().to_radians();
let theta2 = rhs.y().to_radians();
let delta_theta = (rhs.y() - self.y()).to_radians();
let delta_lambda = (rhs.x() - self.x()).to_radians();
let a = (delta_theta / two).sin().powi(2)
+ theta1.cos() * theta2.cos() * (delta_lambda / two).sin().powi(2);
let c = two * a.sqrt().asin();
T::from(MEAN_EARTH_RADIUS).unwrap() * c
}
}
#[cfg(test)]
mod test {
use crate::HaversineDistance;
use crate::Point;
#[test]
fn distance1_test() {
let a = Point::new(0., 0.);
let b = Point::new(1., 0.);
assert_relative_eq!(
a.haversine_distance(&b),
111195.0802335329_f64,
epsilon = 1.0e-6
);
}
#[test]
fn distance2_test() {
let a = Point::new(-72.1235, 42.3521);
let b = Point::new(72.1260, 70.612);
assert_relative_eq!(
a.haversine_distance(&b),
7130580.307935911_f64,
epsilon = 1.0e-6
);
}
#[test]
fn distance3_test() {
let a = Point::new(-77.036585, 38.897448);
let b = Point::new(-77.009080, 38.889825);
assert_relative_eq!(
a.haversine_distance(&b),
2526.823504306046_f64,
epsilon = 1.0e-6
);
}
#[test]
fn distance3_test_f32() {
let a = Point::<f32>::new(-77.03658, 38.89745);
let b = Point::<f32>::new(-77.00908, 38.889825);
assert_relative_eq!(a.haversine_distance(&b), 2526.8354_f32, epsilon = 1.0e-6);
}
}