From 6697efd6278d4049b83553aa7db24c9abe35e3f3 Mon Sep 17 00:00:00 2001 From: Taylor Bockman Date: Tue, 3 Sep 2019 18:20:04 -0700 Subject: [PATCH] Add euclidean distance and tests --- clusterview/math.py | 23 +++++++++++++++++++++++ tests/test_math.py | 19 +++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 clusterview/math.py create mode 100644 tests/test_math.py diff --git a/clusterview/math.py b/clusterview/math.py new file mode 100644 index 0000000..bf8c6eb --- /dev/null +++ b/clusterview/math.py @@ -0,0 +1,23 @@ +import math + +from .points import Point + + +class Math: + """ + Defines useful static helper methods for mathematical functions in + Computational Geometry. + """ + + @classmethod + def euclidean_distance(cls, p1, p2): + """ + Given two points of type Point, returns the euclidean distance between + those two points. + """ + + if not isinstance(p1, Point) or not isinstance(p2, Point): + raise ValueError("Euclidean distance can only be calculated " + + "on points") + + return math.sqrt(math.pow(p2.x - p1.x, 2) + math.pow(p2.y - p1.y, 2)) diff --git a/tests/test_math.py b/tests/test_math.py new file mode 100644 index 0000000..04e3198 --- /dev/null +++ b/tests/test_math.py @@ -0,0 +1,19 @@ +import pytest + +from clusterview.colors import Color +from clusterview.math import Math +from clusterview.points import Point + + +def test_euclidean_distance(): + p1 = Point(150, 100, Color.BLACK, 8, 800, 600) + p2 = Point(300, 200, Color.BLACK, 8, 800, 600) + + d = Math.euclidean_distance(p1, p2) + + assert round(d, 2) == 180.28 + + +def test_euclidean_distance_bad_points(): + with pytest.raises(ValueError): + Math.euclidean_distance(1, 1)