Adds fn to get distance between two points
@@ -9,6 +9,11 @@ impl Point {
pub fn new(x: f64, y: f64) -> Self {
Point { x, y }
}
+
+ /// Returns the distance between this `Point` and the given `Point`.
+ pub fn distance(&self, other: Self) -> f64 {
+ ((self.x - other.x).powf(2.) + (self.y - other.y).powf(2.)).sqrt()
+ }
}
impl From<f64> for Point {
@@ -34,3 +39,15 @@ impl From<(i32, i32)> for Point {
Point::from((s.0 as f64, s.1 as f64))
}
}
+
+#[test]
+fn test_distance() {
+ const EXPECTED_RESULT: f64 = 9.48683;
+ const ERROR_MARGIN: f64 = 0.00001;
+
+ let point_positive = Point { x: 1., y: 5. };
+ let point_negative = Point { x: -2., y: -4. };
+
+ assert!(((point_positive.distance(point_negative) - EXPECTED_RESULT).abs() < ERROR_MARGIN));
+ assert!(((point_negative.distance(point_positive) - EXPECTED_RESULT).abs() < ERROR_MARGIN));
+}
