Skip to main content

use_geometry/
distance.rs

1//! Distance and interpolation helpers for 2D points.
2
3use crate::point::Point2;
4
5/// Returns the Euclidean distance between two 2D points.
6///
7/// # Examples
8///
9/// ```
10/// use use_geometry::{Point2, distance_2d};
11///
12/// let left = Point2::new(0.0, 0.0);
13/// let right = Point2::new(3.0, 4.0);
14///
15/// assert_eq!(distance_2d(left, right), 5.0);
16/// ```
17#[must_use]
18pub fn distance_2d(left: Point2, right: Point2) -> f64 {
19    left.distance_to(right)
20}
21
22/// Returns the squared Euclidean distance between two 2D points.
23///
24/// # Examples
25///
26/// ```
27/// use use_geometry::{Point2, distance_squared_2d};
28///
29/// let left = Point2::new(0.0, 0.0);
30/// let right = Point2::new(3.0, 4.0);
31///
32/// assert_eq!(distance_squared_2d(left, right), 25.0);
33/// ```
34#[must_use]
35pub fn distance_squared_2d(left: Point2, right: Point2) -> f64 {
36    left.distance_squared_to(right)
37}
38
39/// Returns the midpoint between two 2D points.
40///
41/// # Examples
42///
43/// ```
44/// use use_geometry::{Point2, midpoint_2d};
45///
46/// let left = Point2::new(-2.0, 1.0);
47/// let right = Point2::new(4.0, 5.0);
48///
49/// assert_eq!(midpoint_2d(left, right), Point2::new(1.0, 3.0));
50/// ```
51#[must_use]
52pub const fn midpoint_2d(left: Point2, right: Point2) -> Point2 {
53    left.midpoint(right)
54}
55
56#[cfg(test)]
57mod tests {
58    use super::{distance_2d, distance_squared_2d, midpoint_2d};
59    use crate::point::Point2;
60
61    fn approx_eq(left: f64, right: f64) -> bool {
62        (left - right).abs() < 1.0e-10
63    }
64
65    #[test]
66    fn computes_distance() {
67        let left = Point2::new(0.0, 0.0);
68        let right = Point2::new(3.0, 4.0);
69
70        assert!(approx_eq(distance_2d(left, right), 5.0));
71    }
72
73    #[test]
74    fn computes_squared_distance() {
75        let left = Point2::new(-1.0, 2.0);
76        let right = Point2::new(2.0, 6.0);
77
78        assert!(approx_eq(distance_squared_2d(left, right), 25.0));
79    }
80
81    #[test]
82    fn computes_midpoints() {
83        let left = Point2::new(0.0, 0.0);
84        let right = Point2::new(4.0, 2.0);
85
86        assert_eq!(midpoint_2d(left, right), Point2::new(2.0, 1.0));
87    }
88}