Adding ability to calculate vector magnitude.

This commit is contained in:
SkalskiP 2024-01-18 12:46:09 +01:00
parent dca7fb43e5
commit 616fc96ca8
2 changed files with 39 additions and 0 deletions

View File

@ -2,6 +2,7 @@ from __future__ import annotations
from dataclasses import dataclass
from enum import Enum
from math import sqrt
from typing import Tuple
@ -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

View File

@ -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