Skip to content

Commit

Permalink
Adding ability to calculate vector magnitude.
Browse files Browse the repository at this point in the history
  • Loading branch information
SkalskiP committed Jan 18, 2024
1 parent dca7fb4 commit 616fc96
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
13 changes: 13 additions & 0 deletions supervision/geometry/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from dataclasses import dataclass
from enum import Enum
from math import sqrt
from typing import Tuple


Expand Down Expand Up @@ -43,6 +44,18 @@ class Vector:
start: Point
end: Point

@property
def magnitude(self) -> float:
"""
Calculate the magnitude (length) of the vector.
Returns:
float: The magnitude of the vector.
"""
dx = self.end.x - self.start.x
dy = self.end.y - self.start.y
return sqrt(dx ** 2 + dy ** 2)

def cross_product(self, point: Point) -> float:
"""
Calculate the 2D cross product (also known as the vector product or outer
Expand Down
26 changes: 26 additions & 0 deletions test/geometry/test_dataclasses.py → test/geometry/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,29 @@ def test_vector_cross_product(
) -> None:
result = vector.cross_product(point=point)
assert result == expected_result


@pytest.mark.parametrize(
"vector, expected_result",
[
(Vector(start=Point(x=0, y=0), end=Point(x=0, y=0)), 0.0),
(Vector(start=Point(x=1, y=0), end=Point(x=0, y=0)), 1.0),
(Vector(start=Point(x=0, y=1), end=Point(x=0, y=0)), 1.0),
(Vector(start=Point(x=0, y=0), end=Point(x=1, y=0)), 1.0),
(Vector(start=Point(x=0, y=0), end=Point(x=0, y=1)), 1.0),
(Vector(start=Point(x=-1, y=0), end=Point(x=0, y=0)), 1.0),
(Vector(start=Point(x=0, y=-1), end=Point(x=0, y=0)), 1.0),
(Vector(start=Point(x=0, y=0), end=Point(x=-1, y=0)), 1.0),
(Vector(start=Point(x=0, y=0), end=Point(x=0, y=-1)), 1.0),
(Vector(start=Point(x=0, y=0), end=Point(x=3, y=4)), 5.0),
(Vector(start=Point(x=0, y=0), end=Point(x=-3, y=4)), 5.0),
(Vector(start=Point(x=0, y=0), end=Point(x=3, y=-4)), 5.0),
(Vector(start=Point(x=0, y=0), end=Point(x=-3, y=-4)), 5.0),
(Vector(start=Point(x=0, y=0), end=Point(x=4, y=3)), 5.0),
(Vector(start=Point(x=3, y=4), end=Point(x=0, y=0)), 5.0),
(Vector(start=Point(x=4, y=3), end=Point(x=0, y=0)), 5.0),
]
)
def test_vector_magnitude(vector: Vector, expected_result: float) -> None:
result = vector.magnitude
assert result == expected_result

0 comments on commit 616fc96

Please sign in to comment.